Merge branch 'collectd-4.7' into collectd-4.8
[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 #define _BSD_SOURCE /* For struct ip_mreq */
23
24 #include "collectd.h"
25 #include "plugin.h"
26 #include "common.h"
27 #include "configfile.h"
28 #include "utils_fbhash.h"
29 #include "utils_avltree.h"
30 #include "utils_cache.h"
31
32 #include "network.h"
33
34 #if HAVE_PTHREAD_H
35 # include <pthread.h>
36 #endif
37 #if HAVE_SYS_SOCKET_H
38 # include <sys/socket.h>
39 #endif
40 #if HAVE_NETDB_H
41 # include <netdb.h>
42 #endif
43 #if HAVE_NETINET_IN_H
44 # include <netinet/in.h>
45 #endif
46 #if HAVE_ARPA_INET_H
47 # include <arpa/inet.h>
48 #endif
49 #if HAVE_POLL_H
50 # include <poll.h>
51 #endif
52
53 #if HAVE_LIBGCRYPT
54 # include <gcrypt.h>
55 GCRY_THREAD_OPTION_PTHREAD_IMPL;
56 #endif
57
58 #ifndef IPV6_ADD_MEMBERSHIP
59 # ifdef IPV6_JOIN_GROUP
60 #  define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
61 # else
62 #  error "Neither IP_ADD_MEMBERSHIP nor IPV6_JOIN_GROUP is defined"
63 # endif
64 #endif /* !IP_ADD_MEMBERSHIP */
65
66 /*
67  * Maximum size required for encryption / signing:
68  *
69  *    42 bytes for the encryption header
70  * +  64 bytes for the username
71  * -----------
72  * = 106 bytes
73  */
74 #define BUFF_SIG_SIZE 106
75
76 /*
77  * Private data types
78  */
79 #define SECURITY_LEVEL_NONE     0
80 #if HAVE_LIBGCRYPT
81 # define SECURITY_LEVEL_SIGN    1
82 # define SECURITY_LEVEL_ENCRYPT 2
83 #endif
84 struct sockent_client
85 {
86         int fd;
87         struct sockaddr_storage *addr;
88         socklen_t                addrlen;
89 #if HAVE_LIBGCRYPT
90         int security_level;
91         char *username;
92         char *password;
93         gcry_cipher_hd_t cypher;
94         unsigned char password_hash[32];
95 #endif
96 };
97
98 struct sockent_server
99 {
100         int *fd;
101         size_t fd_num;
102 #if HAVE_LIBGCRYPT
103         int security_level;
104         char *auth_file;
105         fbhash_t *userdb;
106         gcry_cipher_hd_t cypher;
107 #endif
108 };
109
110 typedef struct sockent
111 {
112 #define SOCKENT_TYPE_CLIENT 1
113 #define SOCKENT_TYPE_SERVER 2
114         int type;
115
116         char *node;
117         char *service;
118
119         union
120         {
121                 struct sockent_client client;
122                 struct sockent_server server;
123         } data;
124
125         struct sockent *next;
126 } sockent_t;
127
128 /*                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
129  *  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
130  * +-------+-----------------------+-------------------------------+
131  * ! Ver.  !                       ! Length                        !
132  * +-------+-----------------------+-------------------------------+
133  */
134 struct part_header_s
135 {
136         uint16_t type;
137         uint16_t length;
138 };
139 typedef struct part_header_s part_header_t;
140
141 /*                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
142  *  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
143  * +-------------------------------+-------------------------------+
144  * ! Type                          ! Length                        !
145  * +-------------------------------+-------------------------------+
146  * : (Length - 4) Bytes                                            :
147  * +---------------------------------------------------------------+
148  */
149 struct part_string_s
150 {
151         part_header_t *head;
152         char *value;
153 };
154 typedef struct part_string_s part_string_t;
155
156 /*                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
157  *  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
158  * +-------------------------------+-------------------------------+
159  * ! Type                          ! Length                        !
160  * +-------------------------------+-------------------------------+
161  * : (Length - 4 == 2 || 4 || 8) Bytes                             :
162  * +---------------------------------------------------------------+
163  */
164 struct part_number_s
165 {
166         part_header_t *head;
167         uint64_t *value;
168 };
169 typedef struct part_number_s part_number_t;
170
171 /*                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
172  *  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
173  * +-------------------------------+-------------------------------+
174  * ! Type                          ! Length                        !
175  * +-------------------------------+---------------+---------------+
176  * ! Num of values                 ! Type0         ! Type1         !
177  * +-------------------------------+---------------+---------------+
178  * ! Value0                                                        !
179  * !                                                               !
180  * +---------------------------------------------------------------+
181  * ! Value1                                                        !
182  * !                                                               !
183  * +---------------------------------------------------------------+
184  */
185 struct part_values_s
186 {
187         part_header_t *head;
188         uint16_t *num_values;
189         uint8_t  *values_types;
190         value_t  *values;
191 };
192 typedef struct part_values_s part_values_t;
193
194 /*                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
195  *  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
196  * +-------------------------------+-------------------------------+
197  * ! Type                          ! Length                        !
198  * +-------------------------------+-------------------------------+
199  * ! Hash (Bits   0 -  31)                                         !
200  * : :                                                             :
201  * ! Hash (Bits 224 - 255)                                         !
202  * +---------------------------------------------------------------+
203  */
204 /* Minimum size */
205 #define PART_SIGNATURE_SHA256_SIZE 36
206 struct part_signature_sha256_s
207 {
208   part_header_t head;
209   unsigned char hash[32];
210   char *username;
211 };
212 typedef struct part_signature_sha256_s part_signature_sha256_t;
213
214 /*                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
215  *  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
216  * +-------------------------------+-------------------------------+
217  * ! Type                          ! Length                        !
218  * +-------------------------------+-------------------------------+
219  * ! Original length               ! Padding (0 - 15 bytes)        !
220  * +-------------------------------+-------------------------------+
221  * ! Hash (Bits   0 -  31)                                         !
222  * : :                                                             :
223  * ! Hash (Bits 128 - 159)                                         !
224  * +---------------------------------------------------------------+
225  */
226 /* Minimum size */
227 #define PART_ENCRYPTION_AES256_SIZE 42
228 struct part_encryption_aes256_s
229 {
230   part_header_t head;
231   uint16_t username_length;
232   char *username;
233   unsigned char iv[16];
234   /* <encrypted> */
235   unsigned char hash[20];
236   /*   <payload /> */
237   /* </encrypted> */
238 };
239 typedef struct part_encryption_aes256_s part_encryption_aes256_t;
240
241 struct receive_list_entry_s
242 {
243   char *data;
244   int  data_len;
245   int  fd;
246   struct receive_list_entry_s *next;
247 };
248 typedef struct receive_list_entry_s receive_list_entry_t;
249
250 /*
251  * Private variables
252  */
253 static int network_config_ttl = 0;
254 static size_t network_config_packet_size = 1024;
255 static int network_config_forward = 0;
256
257 static sockent_t *sending_sockets = NULL;
258
259 static receive_list_entry_t *receive_list_head = NULL;
260 static receive_list_entry_t *receive_list_tail = NULL;
261 static pthread_mutex_t       receive_list_lock = PTHREAD_MUTEX_INITIALIZER;
262 static pthread_cond_t        receive_list_cond = PTHREAD_COND_INITIALIZER;
263
264 static sockent_t     *listen_sockets = NULL;
265 static struct pollfd *listen_sockets_pollfd = NULL;
266 static size_t         listen_sockets_num = 0;
267
268 /* The receive and dispatch threads will run as long as `listen_loop' is set to
269  * zero. */
270 static int       listen_loop = 0;
271 static int       receive_thread_running = 0;
272 static pthread_t receive_thread_id;
273 static int       dispatch_thread_running = 0;
274 static pthread_t dispatch_thread_id;
275
276 /* Buffer in which to-be-sent network packets are constructed. */
277 static char            *send_buffer;
278 static char            *send_buffer_ptr;
279 static int              send_buffer_fill;
280 static value_list_t     send_buffer_vl = VALUE_LIST_STATIC;
281 static pthread_mutex_t  send_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
282
283 /*
284  * Private functions
285  */
286 static _Bool check_receive_okay (const value_list_t *vl) /* {{{ */
287 {
288   uint64_t time_sent = 0;
289   int status;
290
291   status = uc_meta_data_get_unsigned_int (vl,
292       "network:time_sent", &time_sent);
293
294   /* This is a value we already sent. Don't allow it to be received again in
295    * order to avoid looping. */
296   if ((status == 0) && (time_sent >= ((uint64_t) vl->time)))
297     return (false);
298
299   return (true);
300 } /* }}} _Bool check_receive_okay */
301
302 static _Bool check_send_okay (const value_list_t *vl) /* {{{ */
303 {
304   _Bool received = false;
305   int status;
306
307   if (network_config_forward != 0)
308     return (true);
309
310   if (vl->meta == NULL)
311     return (true);
312
313   status = meta_data_get_boolean (vl->meta, "network:received", &received);
314   if (status == -ENOENT)
315     return (true);
316   else if (status != 0)
317   {
318     ERROR ("network plugin: check_send_okay: meta_data_get_boolean failed "
319         "with status %i.", status);
320     return (true);
321   }
322
323   /* By default, only *send* value lists that were not *received* by the
324    * network plugin. */
325   return (!received);
326 } /* }}} _Bool check_send_okay */
327
328 static int network_dispatch_values (value_list_t *vl) /* {{{ */
329 {
330   int status;
331
332   if ((vl->time <= 0)
333       || (strlen (vl->host) <= 0)
334       || (strlen (vl->plugin) <= 0)
335       || (strlen (vl->type) <= 0))
336     return (-EINVAL);
337
338   if (!check_receive_okay (vl))
339   {
340 #if COLLECT_DEBUG
341           char name[6*DATA_MAX_NAME_LEN];
342           FORMAT_VL (name, sizeof (name), vl);
343           name[sizeof (name) - 1] = 0;
344           DEBUG ("network plugin: network_dispatch_values: "
345               "NOT dispatching %s.", name);
346 #endif
347     return (0);
348   }
349
350   assert (vl->meta == NULL);
351
352   vl->meta = meta_data_create ();
353   if (vl->meta == NULL)
354   {
355     ERROR ("network plugin: meta_data_create failed.");
356     return (-ENOMEM);
357   }
358
359   status = meta_data_add_boolean (vl->meta, "network:received", true);
360   if (status != 0)
361   {
362     ERROR ("network plugin: meta_data_add_boolean failed.");
363     meta_data_destroy (vl->meta);
364     vl->meta = NULL;
365     return (status);
366   }
367
368   plugin_dispatch_values (vl);
369
370   meta_data_destroy (vl->meta);
371   vl->meta = NULL;
372
373   return (0);
374 } /* }}} int network_dispatch_values */
375
376 #if HAVE_LIBGCRYPT
377 static gcry_cipher_hd_t network_get_aes256_cypher (sockent_t *se, /* {{{ */
378     const void *iv, size_t iv_size, const char *username)
379 {
380   gcry_error_t err;
381   gcry_cipher_hd_t *cyper_ptr;
382   unsigned char password_hash[32];
383
384   if (se->type == SOCKENT_TYPE_CLIENT)
385   {
386           cyper_ptr = &se->data.client.cypher;
387           memcpy (password_hash, se->data.client.password_hash,
388                           sizeof (password_hash));
389   }
390   else
391   {
392           char *secret;
393
394           cyper_ptr = &se->data.server.cypher;
395
396           if (username == NULL)
397                   return (NULL);
398
399           secret = fbh_get (se->data.server.userdb, username);
400           if (secret == NULL)
401                   return (NULL);
402
403           gcry_md_hash_buffer (GCRY_MD_SHA256,
404                           password_hash,
405                           secret, strlen (secret));
406
407           sfree (secret);
408   }
409
410   if (*cyper_ptr == NULL)
411   {
412     err = gcry_cipher_open (cyper_ptr,
413         GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB, /* flags = */ 0);
414     if (err != 0)
415     {
416       ERROR ("network plugin: gcry_cipher_open returned: %s",
417           gcry_strerror (err));
418       *cyper_ptr = NULL;
419       return (NULL);
420     }
421   }
422   else
423   {
424     gcry_cipher_reset (*cyper_ptr);
425   }
426   assert (*cyper_ptr != NULL);
427
428   err = gcry_cipher_setkey (*cyper_ptr,
429       password_hash, sizeof (password_hash));
430   if (err != 0)
431   {
432     ERROR ("network plugin: gcry_cipher_setkey returned: %s",
433         gcry_strerror (err));
434     gcry_cipher_close (*cyper_ptr);
435     *cyper_ptr = NULL;
436     return (NULL);
437   }
438
439   err = gcry_cipher_setiv (*cyper_ptr, iv, iv_size);
440   if (err != 0)
441   {
442     ERROR ("network plugin: gcry_cipher_setkey returned: %s",
443         gcry_strerror (err));
444     gcry_cipher_close (*cyper_ptr);
445     *cyper_ptr = NULL;
446     return (NULL);
447   }
448
449   return (*cyper_ptr);
450 } /* }}} int network_get_aes256_cypher */
451 #endif /* HAVE_LIBGCRYPT */
452
453 static int write_part_values (char **ret_buffer, int *ret_buffer_len,
454                 const data_set_t *ds, const value_list_t *vl)
455 {
456         char *packet_ptr;
457         int packet_len;
458         int num_values;
459
460         part_header_t pkg_ph;
461         uint16_t      pkg_num_values;
462         uint8_t      *pkg_values_types;
463         value_t      *pkg_values;
464
465         int offset;
466         int i;
467
468         num_values = vl->values_len;
469         packet_len = sizeof (part_header_t) + sizeof (uint16_t)
470                 + (num_values * sizeof (uint8_t))
471                 + (num_values * sizeof (value_t));
472
473         if (*ret_buffer_len < packet_len)
474                 return (-1);
475
476         pkg_values_types = (uint8_t *) malloc (num_values * sizeof (uint8_t));
477         if (pkg_values_types == NULL)
478         {
479                 ERROR ("network plugin: write_part_values: malloc failed.");
480                 return (-1);
481         }
482
483         pkg_values = (value_t *) malloc (num_values * sizeof (value_t));
484         if (pkg_values == NULL)
485         {
486                 free (pkg_values_types);
487                 ERROR ("network plugin: write_part_values: malloc failed.");
488                 return (-1);
489         }
490
491         pkg_ph.type = htons (TYPE_VALUES);
492         pkg_ph.length = htons (packet_len);
493
494         pkg_num_values = htons ((uint16_t) vl->values_len);
495
496         for (i = 0; i < num_values; i++)
497         {
498                 pkg_values_types[i] = (uint8_t) ds->ds[i].type;
499                 switch (ds->ds[i].type)
500                 {
501                         case DS_TYPE_COUNTER:
502                                 pkg_values[i].counter = htonll (vl->values[i].counter);
503                                 break;
504
505                         case DS_TYPE_GAUGE:
506                                 pkg_values[i].gauge = htond (vl->values[i].gauge);
507                                 break;
508
509                         case DS_TYPE_DERIVE:
510                                 pkg_values[i].derive = htonll (vl->values[i].derive);
511                                 break;
512
513                         case DS_TYPE_ABSOLUTE:
514                                 pkg_values[i].absolute = htonll (vl->values[i].absolute);
515                                 break;
516
517                         default:
518                                 free (pkg_values_types);
519                                 free (pkg_values);
520                                 ERROR ("network plugin: write_part_values: "
521                                                 "Unknown data source type: %i",
522                                                 ds->ds[i].type);
523                                 return (-1);
524                 } /* switch (ds->ds[i].type) */
525         } /* for (num_values) */
526
527         /*
528          * Use `memcpy' to write everything to the buffer, because the pointer
529          * may be unaligned and some architectures, such as SPARC, can't handle
530          * that.
531          */
532         packet_ptr = *ret_buffer;
533         offset = 0;
534         memcpy (packet_ptr + offset, &pkg_ph, sizeof (pkg_ph));
535         offset += sizeof (pkg_ph);
536         memcpy (packet_ptr + offset, &pkg_num_values, sizeof (pkg_num_values));
537         offset += sizeof (pkg_num_values);
538         memcpy (packet_ptr + offset, pkg_values_types, num_values * sizeof (uint8_t));
539         offset += num_values * sizeof (uint8_t);
540         memcpy (packet_ptr + offset, pkg_values, num_values * sizeof (value_t));
541         offset += num_values * sizeof (value_t);
542
543         assert (offset == packet_len);
544
545         *ret_buffer = packet_ptr + packet_len;
546         *ret_buffer_len -= packet_len;
547
548         free (pkg_values_types);
549         free (pkg_values);
550
551         return (0);
552 } /* int write_part_values */
553
554 static int write_part_number (char **ret_buffer, int *ret_buffer_len,
555                 int type, uint64_t value)
556 {
557         char *packet_ptr;
558         int packet_len;
559
560         part_header_t pkg_head;
561         uint64_t pkg_value;
562         
563         int offset;
564
565         packet_len = sizeof (pkg_head) + sizeof (pkg_value);
566
567         if (*ret_buffer_len < packet_len)
568                 return (-1);
569
570         pkg_head.type = htons (type);
571         pkg_head.length = htons (packet_len);
572         pkg_value = htonll (value);
573
574         packet_ptr = *ret_buffer;
575         offset = 0;
576         memcpy (packet_ptr + offset, &pkg_head, sizeof (pkg_head));
577         offset += sizeof (pkg_head);
578         memcpy (packet_ptr + offset, &pkg_value, sizeof (pkg_value));
579         offset += sizeof (pkg_value);
580
581         assert (offset == packet_len);
582
583         *ret_buffer = packet_ptr + packet_len;
584         *ret_buffer_len -= packet_len;
585
586         return (0);
587 } /* int write_part_number */
588
589 static int write_part_string (char **ret_buffer, int *ret_buffer_len,
590                 int type, const char *str, int str_len)
591 {
592         char *buffer;
593         int buffer_len;
594
595         uint16_t pkg_type;
596         uint16_t pkg_length;
597
598         int offset;
599
600         buffer_len = 2 * sizeof (uint16_t) + str_len + 1;
601         if (*ret_buffer_len < buffer_len)
602                 return (-1);
603
604         pkg_type = htons (type);
605         pkg_length = htons (buffer_len);
606
607         buffer = *ret_buffer;
608         offset = 0;
609         memcpy (buffer + offset, (void *) &pkg_type, sizeof (pkg_type));
610         offset += sizeof (pkg_type);
611         memcpy (buffer + offset, (void *) &pkg_length, sizeof (pkg_length));
612         offset += sizeof (pkg_length);
613         memcpy (buffer + offset, str, str_len);
614         offset += str_len;
615         memset (buffer + offset, '\0', 1);
616         offset += 1;
617
618         assert (offset == buffer_len);
619
620         *ret_buffer = buffer + buffer_len;
621         *ret_buffer_len -= buffer_len;
622
623         return (0);
624 } /* int write_part_string */
625
626 static int parse_part_values (void **ret_buffer, size_t *ret_buffer_len,
627                 value_t **ret_values, int *ret_num_values)
628 {
629         char *buffer = *ret_buffer;
630         size_t buffer_len = *ret_buffer_len;
631
632         uint16_t tmp16;
633         size_t exp_size;
634         int   i;
635
636         uint16_t pkg_length;
637         uint16_t pkg_type;
638         uint16_t pkg_numval;
639
640         uint8_t *pkg_types;
641         value_t *pkg_values;
642
643         if (buffer_len < 15)
644         {
645                 NOTICE ("network plugin: packet is too short: "
646                                 "buffer_len = %zu", buffer_len);
647                 return (-1);
648         }
649
650         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
651         buffer += sizeof (tmp16);
652         pkg_type = ntohs (tmp16);
653
654         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
655         buffer += sizeof (tmp16);
656         pkg_length = ntohs (tmp16);
657
658         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
659         buffer += sizeof (tmp16);
660         pkg_numval = ntohs (tmp16);
661
662         assert (pkg_type == TYPE_VALUES);
663
664         exp_size = 3 * sizeof (uint16_t)
665                 + pkg_numval * (sizeof (uint8_t) + sizeof (value_t));
666         if ((buffer_len < 0) || (buffer_len < exp_size))
667         {
668                 WARNING ("network plugin: parse_part_values: "
669                                 "Packet too short: "
670                                 "Chunk of size %zu expected, "
671                                 "but buffer has only %zu bytes left.",
672                                 exp_size, buffer_len);
673                 return (-1);
674         }
675
676         if (pkg_length != exp_size)
677         {
678                 WARNING ("network plugin: parse_part_values: "
679                                 "Length and number of values "
680                                 "in the packet don't match.");
681                 return (-1);
682         }
683
684         pkg_types = (uint8_t *) malloc (pkg_numval * sizeof (uint8_t));
685         pkg_values = (value_t *) malloc (pkg_numval * sizeof (value_t));
686         if ((pkg_types == NULL) || (pkg_values == NULL))
687         {
688                 sfree (pkg_types);
689                 sfree (pkg_values);
690                 ERROR ("network plugin: parse_part_values: malloc failed.");
691                 return (-1);
692         }
693
694         memcpy ((void *) pkg_types, (void *) buffer, pkg_numval * sizeof (uint8_t));
695         buffer += pkg_numval * sizeof (uint8_t);
696         memcpy ((void *) pkg_values, (void *) buffer, pkg_numval * sizeof (value_t));
697         buffer += pkg_numval * sizeof (value_t);
698
699         for (i = 0; i < pkg_numval; i++)
700         {
701                 switch (pkg_types[i])
702                 {
703                   case DS_TYPE_COUNTER:
704                     pkg_values[i].counter = (counter_t) ntohll (pkg_values[i].counter);
705                     break;
706
707                   case DS_TYPE_GAUGE:
708                     pkg_values[i].gauge = (gauge_t) ntohd (pkg_values[i].gauge);
709                     break;
710
711                   case DS_TYPE_DERIVE:
712                     pkg_values[i].derive = (derive_t) ntohll (pkg_values[i].derive);
713                     break;
714
715                   case DS_TYPE_ABSOLUTE:
716                     pkg_values[i].absolute = (absolute_t) ntohll (pkg_values[i].absolute);
717                     break;
718
719                   default:
720                     sfree (pkg_types);
721                     sfree (pkg_values);
722                     NOTICE ("network plugin: parse_part_values: "
723                         "Don't know how to handle data source type %"PRIu8,
724                         pkg_types[i]);
725                     return (-1);
726                 } /* switch (pkg_types[i]) */
727         }
728
729         *ret_buffer     = buffer;
730         *ret_buffer_len = buffer_len - pkg_length;
731         *ret_num_values = pkg_numval;
732         *ret_values     = pkg_values;
733
734         sfree (pkg_types);
735
736         return (0);
737 } /* int parse_part_values */
738
739 static int parse_part_number (void **ret_buffer, size_t *ret_buffer_len,
740                 uint64_t *value)
741 {
742         char *buffer = *ret_buffer;
743         size_t buffer_len = *ret_buffer_len;
744
745         uint16_t tmp16;
746         uint64_t tmp64;
747         size_t exp_size = 2 * sizeof (uint16_t) + sizeof (uint64_t);
748
749         uint16_t pkg_length;
750         uint16_t pkg_type;
751
752         if ((buffer_len < 0) || ((size_t) buffer_len < exp_size))
753         {
754                 WARNING ("network plugin: parse_part_number: "
755                                 "Packet too short: "
756                                 "Chunk of size %zu expected, "
757                                 "but buffer has only %zu bytes left.",
758                                 exp_size, buffer_len);
759                 return (-1);
760         }
761
762         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
763         buffer += sizeof (tmp16);
764         pkg_type = ntohs (tmp16);
765
766         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
767         buffer += sizeof (tmp16);
768         pkg_length = ntohs (tmp16);
769
770         memcpy ((void *) &tmp64, buffer, sizeof (tmp64));
771         buffer += sizeof (tmp64);
772         *value = ntohll (tmp64);
773
774         *ret_buffer = buffer;
775         *ret_buffer_len = buffer_len - pkg_length;
776
777         return (0);
778 } /* int parse_part_number */
779
780 static int parse_part_string (void **ret_buffer, size_t *ret_buffer_len,
781                 char *output, int output_len)
782 {
783         char *buffer = *ret_buffer;
784         size_t buffer_len = *ret_buffer_len;
785
786         uint16_t tmp16;
787         size_t header_size = 2 * sizeof (uint16_t);
788
789         uint16_t pkg_length;
790         uint16_t pkg_type;
791
792         if ((buffer_len < 0) || (buffer_len < header_size))
793         {
794                 WARNING ("network plugin: parse_part_string: "
795                                 "Packet too short: "
796                                 "Chunk of at least size %zu expected, "
797                                 "but buffer has only %zu bytes left.",
798                                 header_size, buffer_len);
799                 return (-1);
800         }
801
802         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
803         buffer += sizeof (tmp16);
804         pkg_type = ntohs (tmp16);
805
806         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
807         buffer += sizeof (tmp16);
808         pkg_length = ntohs (tmp16);
809
810         /* Check that packet fits in the input buffer */
811         if (pkg_length > buffer_len)
812         {
813                 WARNING ("network plugin: parse_part_string: "
814                                 "Packet too big: "
815                                 "Chunk of size %"PRIu16" received, "
816                                 "but buffer has only %zu bytes left.",
817                                 pkg_length, buffer_len);
818                 return (-1);
819         }
820
821         /* Check that pkg_length is in the valid range */
822         if (pkg_length <= header_size)
823         {
824                 WARNING ("network plugin: parse_part_string: "
825                                 "Packet too short: "
826                                 "Header claims this packet is only %hu "
827                                 "bytes long.", pkg_length);
828                 return (-1);
829         }
830
831         /* Check that the package data fits into the output buffer.
832          * The previous if-statement ensures that:
833          * `pkg_length > header_size' */
834         if ((output_len < 0)
835                         || ((size_t) output_len < ((size_t) pkg_length - header_size)))
836         {
837                 WARNING ("network plugin: parse_part_string: "
838                                 "Output buffer too small.");
839                 return (-1);
840         }
841
842         /* All sanity checks successfull, let's copy the data over */
843         output_len = pkg_length - header_size;
844         memcpy ((void *) output, (void *) buffer, output_len);
845         buffer += output_len;
846
847         /* For some very weird reason '\0' doesn't do the trick on SPARC in
848          * this statement. */
849         if (output[output_len - 1] != 0)
850         {
851                 WARNING ("network plugin: parse_part_string: "
852                                 "Received string does not end "
853                                 "with a NULL-byte.");
854                 return (-1);
855         }
856
857         *ret_buffer = buffer;
858         *ret_buffer_len = buffer_len - pkg_length;
859
860         return (0);
861 } /* int parse_part_string */
862
863 /* Forward declaration: parse_part_sign_sha256 and parse_part_encr_aes256 call
864  * parse_packet and vice versa. */
865 #define PP_SIGNED    0x01
866 #define PP_ENCRYPTED 0x02
867 static int parse_packet (sockent_t *se,
868                 void *buffer, size_t buffer_size, int flags);
869
870 #define BUFFER_READ(p,s) do { \
871   memcpy ((p), buffer + buffer_offset, (s)); \
872   buffer_offset += (s); \
873 } while (0)
874
875 #if HAVE_LIBGCRYPT
876 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
877     void **ret_buffer, size_t *ret_buffer_len, int flags)
878 {
879   char *buffer;
880   size_t buffer_len;
881   size_t buffer_offset;
882
883   size_t username_len;
884   char *secret;
885
886   part_signature_sha256_t pss;
887   uint16_t pss_head_length;
888   char hash[sizeof (pss.hash)];
889
890   gcry_md_hd_t hd;
891   gcry_error_t err;
892   unsigned char *hash_ptr;
893
894   buffer = *ret_buffer;
895   buffer_len = *ret_buffer_len;
896   buffer_offset = 0;
897
898   if (se->data.server.userdb == NULL)
899   {
900     NOTICE ("network plugin: Received signed network packet but can't verify "
901         "it because no user DB has been configured. Will accept it.");
902     return (0);
903   }
904
905   /* Check if the buffer has enough data for this structure. */
906   if (buffer_len <= PART_SIGNATURE_SHA256_SIZE)
907     return (-ENOMEM);
908
909   /* Read type and length header */
910   BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
911   BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
912   pss_head_length = ntohs (pss.head.length);
913
914   /* Check if the `pss_head_length' is within bounds. */
915   if ((pss_head_length <= PART_SIGNATURE_SHA256_SIZE)
916       || (pss_head_length > buffer_len))
917   {
918     ERROR ("network plugin: HMAC-SHA-256 with invalid length received.");
919     return (-1);
920   }
921
922   /* Copy the hash. */
923   BUFFER_READ (pss.hash, sizeof (pss.hash));
924
925   /* Calculate username length (without null byte) and allocate memory */
926   username_len = pss_head_length - PART_SIGNATURE_SHA256_SIZE;
927   pss.username = malloc (username_len + 1);
928   if (pss.username == NULL)
929     return (-ENOMEM);
930
931   /* Read the username */
932   BUFFER_READ (pss.username, username_len);
933   pss.username[username_len] = 0;
934
935   assert (buffer_offset == pss_head_length);
936
937   /* Query the password */
938   secret = fbh_get (se->data.server.userdb, pss.username);
939   if (secret == NULL)
940   {
941     ERROR ("network plugin: Unknown user: %s", pss.username);
942     sfree (pss.username);
943     return (-ENOENT);
944   }
945
946   /* Create a hash device and check the HMAC */
947   hd = NULL;
948   err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
949   if (err != 0)
950   {
951     ERROR ("network plugin: Creating HMAC-SHA-256 object failed: %s",
952         gcry_strerror (err));
953     sfree (secret);
954     sfree (pss.username);
955     return (-1);
956   }
957
958   err = gcry_md_setkey (hd, secret, strlen (secret));
959   if (err != 0)
960   {
961     ERROR ("network plugin: gcry_md_setkey failed: %s", gcry_strerror (err));
962     gcry_md_close (hd);
963     return (-1);
964   }
965
966   gcry_md_write (hd,
967       buffer     + PART_SIGNATURE_SHA256_SIZE,
968       buffer_len - PART_SIGNATURE_SHA256_SIZE);
969   hash_ptr = gcry_md_read (hd, GCRY_MD_SHA256);
970   if (hash_ptr == NULL)
971   {
972     ERROR ("network plugin: gcry_md_read failed.");
973     gcry_md_close (hd);
974     sfree (secret);
975     sfree (pss.username);
976     return (-1);
977   }
978   memcpy (hash, hash_ptr, sizeof (hash));
979
980   /* Clean up */
981   gcry_md_close (hd);
982   hd = NULL;
983
984   sfree (secret);
985   sfree (pss.username);
986
987   if (memcmp (pss.hash, hash, sizeof (pss.hash)) != 0)
988   {
989     WARNING ("network plugin: Verifying HMAC-SHA-256 signature failed: "
990         "Hash mismatch.");
991   }
992   else
993   {
994     parse_packet (se, buffer + buffer_offset, buffer_len - buffer_offset,
995         flags | PP_SIGNED);
996   }
997
998   *ret_buffer = buffer + buffer_len;
999   *ret_buffer_len = 0;
1000
1001   return (0);
1002 } /* }}} int parse_part_sign_sha256 */
1003 /* #endif HAVE_LIBGCRYPT */
1004
1005 #else /* if !HAVE_LIBGCRYPT */
1006 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
1007     void **ret_buffer, size_t *ret_buffer_size, int flags)
1008 {
1009   static int warning_has_been_printed = 0;
1010
1011   char *buffer;
1012   size_t buffer_size;
1013   size_t buffer_offset;
1014   uint16_t part_len;
1015
1016   part_signature_sha256_t pss;
1017
1018   buffer = *ret_buffer;
1019   buffer_size = *ret_buffer_size;
1020   buffer_offset = 0;
1021
1022   if (buffer_size <= PART_SIGNATURE_SHA256_SIZE)
1023     return (-ENOMEM);
1024
1025   BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1026   BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1027   part_len = ntohs (pss.head.length);
1028
1029   if ((part_len <= PART_SIGNATURE_SHA256_SIZE)
1030       || (part_len > buffer_size))
1031     return (-EINVAL);
1032
1033   if (warning_has_been_printed == 0)
1034   {
1035     WARNING ("network plugin: Received signed packet, but the network "
1036         "plugin was not linked with libgcrypt, so I cannot "
1037         "verify the signature. The packet will be accepted.");
1038     warning_has_been_printed = 1;
1039   }
1040
1041   parse_packet (se, buffer + part_len, buffer_size - part_len, flags);
1042
1043   *ret_buffer = buffer + buffer_size;
1044   *ret_buffer_size = 0;
1045
1046   return (0);
1047 } /* }}} int parse_part_sign_sha256 */
1048 #endif /* !HAVE_LIBGCRYPT */
1049
1050 #if HAVE_LIBGCRYPT
1051 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1052                 void **ret_buffer, size_t *ret_buffer_len,
1053                 int flags)
1054 {
1055   char  *buffer = *ret_buffer;
1056   size_t buffer_len = *ret_buffer_len;
1057   size_t payload_len;
1058   size_t part_size;
1059   size_t buffer_offset;
1060   uint16_t username_len;
1061   part_encryption_aes256_t pea;
1062   unsigned char hash[sizeof (pea.hash)];
1063
1064   gcry_cipher_hd_t cypher;
1065   gcry_error_t err;
1066
1067   /* Make sure at least the header if available. */
1068   if (buffer_len <= PART_ENCRYPTION_AES256_SIZE)
1069   {
1070     NOTICE ("network plugin: parse_part_encr_aes256: "
1071         "Discarding short packet.");
1072     return (-1);
1073   }
1074
1075   buffer_offset = 0;
1076
1077   /* Copy the unencrypted information into `pea'. */
1078   BUFFER_READ (&pea.head.type, sizeof (pea.head.type));
1079   BUFFER_READ (&pea.head.length, sizeof (pea.head.length));
1080
1081   /* Check the `part size'. */
1082   part_size = ntohs (pea.head.length);
1083   if ((part_size <= PART_ENCRYPTION_AES256_SIZE)
1084       || (part_size > buffer_len))
1085   {
1086     NOTICE ("network plugin: parse_part_encr_aes256: "
1087         "Discarding part with invalid size.");
1088     return (-1);
1089   }
1090
1091   /* Read the username */
1092   BUFFER_READ (&username_len, sizeof (username_len));
1093   username_len = ntohs (username_len);
1094
1095   if ((username_len <= 0)
1096       || (username_len > (part_size - (PART_ENCRYPTION_AES256_SIZE + 1))))
1097   {
1098     NOTICE ("network plugin: parse_part_encr_aes256: "
1099         "Discarding part with invalid username length.");
1100     return (-1);
1101   }
1102
1103   assert (username_len > 0);
1104   pea.username = malloc (username_len + 1);
1105   if (pea.username == NULL)
1106     return (-ENOMEM);
1107   BUFFER_READ (pea.username, username_len);
1108   pea.username[username_len] = 0;
1109
1110   /* Last but not least, the initialization vector */
1111   BUFFER_READ (pea.iv, sizeof (pea.iv));
1112
1113   /* Make sure we are at the right position */
1114   assert (buffer_offset == (username_len +
1115         PART_ENCRYPTION_AES256_SIZE - sizeof (pea.hash)));
1116
1117   cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
1118       pea.username);
1119   if (cypher == NULL)
1120     return (-1);
1121
1122   payload_len = part_size - (PART_ENCRYPTION_AES256_SIZE + username_len);
1123   assert (payload_len > 0);
1124
1125   /* Decrypt the packet in-place */
1126   err = gcry_cipher_decrypt (cypher,
1127       buffer    + buffer_offset,
1128       part_size - buffer_offset,
1129       /* in = */ NULL, /* in len = */ 0);
1130   if (err != 0)
1131   {
1132     ERROR ("network plugin: gcry_cipher_decrypt returned: %s",
1133         gcry_strerror (err));
1134     return (-1);
1135   }
1136
1137   /* Read the hash */
1138   BUFFER_READ (pea.hash, sizeof (pea.hash));
1139
1140   /* Make sure we're at the right position - again */
1141   assert (buffer_offset == (username_len + PART_ENCRYPTION_AES256_SIZE));
1142   assert (buffer_offset == (part_size - payload_len));
1143
1144   /* Check hash sum */
1145   memset (hash, 0, sizeof (hash));
1146   gcry_md_hash_buffer (GCRY_MD_SHA1, hash,
1147       buffer + buffer_offset, payload_len);
1148   if (memcmp (hash, pea.hash, sizeof (hash)) != 0)
1149   {
1150     ERROR ("network plugin: Decryption failed: Checksum mismatch.");
1151     return (-1);
1152   }
1153
1154   parse_packet (se, buffer + buffer_offset, payload_len,
1155       flags | PP_ENCRYPTED);
1156
1157   /* Update return values */
1158   *ret_buffer =     buffer     + part_size;
1159   *ret_buffer_len = buffer_len - part_size;
1160
1161   return (0);
1162 } /* }}} int parse_part_encr_aes256 */
1163 /* #endif HAVE_LIBGCRYPT */
1164
1165 #else /* if !HAVE_LIBGCRYPT */
1166 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1167     void **ret_buffer, size_t *ret_buffer_size, int flags)
1168 {
1169   static int warning_has_been_printed = 0;
1170
1171   char *buffer;
1172   size_t buffer_size;
1173   size_t buffer_offset;
1174
1175   part_header_t ph;
1176   size_t ph_length;
1177
1178   buffer = *ret_buffer;
1179   buffer_size = *ret_buffer_size;
1180   buffer_offset = 0;
1181
1182   /* parse_packet assures this minimum size. */
1183   assert (buffer_size >= (sizeof (ph.type) + sizeof (ph.length)));
1184
1185   BUFFER_READ (&ph.type, sizeof (ph.type));
1186   BUFFER_READ (&ph.length, sizeof (ph.length));
1187   ph_length = ntohs (ph.length);
1188
1189   if ((ph_length <= PART_ENCRYPTION_AES256_SIZE)
1190       || (ph_length > buffer_size))
1191   {
1192     ERROR ("network plugin: AES-256 encrypted part "
1193         "with invalid length received.");
1194     return (-1);
1195   }
1196
1197   if (warning_has_been_printed == 0)
1198   {
1199     WARNING ("network plugin: Received encrypted packet, but the network "
1200         "plugin was not linked with libgcrypt, so I cannot "
1201         "decrypt it. The part will be discarded.");
1202     warning_has_been_printed = 1;
1203   }
1204
1205   *ret_buffer += ph_length;
1206   *ret_buffer_size -= ph_length;
1207
1208   return (0);
1209 } /* }}} int parse_part_encr_aes256 */
1210 #endif /* !HAVE_LIBGCRYPT */
1211
1212 #undef BUFFER_READ
1213
1214 static int parse_packet (sockent_t *se, /* {{{ */
1215                 void *buffer, size_t buffer_size, int flags)
1216 {
1217         int status;
1218
1219         value_list_t vl = VALUE_LIST_INIT;
1220         notification_t n;
1221
1222 #if HAVE_LIBGCRYPT
1223         int packet_was_signed = (flags & PP_SIGNED);
1224         int packet_was_encrypted = (flags & PP_ENCRYPTED);
1225         int printed_ignore_warning = 0;
1226 #endif /* HAVE_LIBGCRYPT */
1227
1228
1229         memset (&vl, '\0', sizeof (vl));
1230         memset (&n, '\0', sizeof (n));
1231         status = 0;
1232
1233         while ((status == 0) && (0 < buffer_size)
1234                         && ((unsigned int) buffer_size > sizeof (part_header_t)))
1235         {
1236                 uint16_t pkg_length;
1237                 uint16_t pkg_type;
1238
1239                 memcpy ((void *) &pkg_type,
1240                                 (void *) buffer,
1241                                 sizeof (pkg_type));
1242                 memcpy ((void *) &pkg_length,
1243                                 (void *) (buffer + sizeof (pkg_type)),
1244                                 sizeof (pkg_length));
1245
1246                 pkg_length = ntohs (pkg_length);
1247                 pkg_type = ntohs (pkg_type);
1248
1249                 if (pkg_length > buffer_size)
1250                         break;
1251                 /* Ensure that this loop terminates eventually */
1252                 if (pkg_length < (2 * sizeof (uint16_t)))
1253                         break;
1254
1255                 if (pkg_type == TYPE_ENCR_AES256)
1256                 {
1257                         status = parse_part_encr_aes256 (se,
1258                                         &buffer, &buffer_size, flags);
1259                         if (status != 0)
1260                         {
1261                                 ERROR ("network plugin: Decrypting AES256 "
1262                                                 "part failed "
1263                                                 "with status %i.", status);
1264                                 break;
1265                         }
1266                 }
1267 #if HAVE_LIBGCRYPT
1268                 else if ((se->data.server.security_level == SECURITY_LEVEL_ENCRYPT)
1269                                 && (packet_was_encrypted == 0))
1270                 {
1271                         if (printed_ignore_warning == 0)
1272                         {
1273                                 INFO ("network plugin: Unencrypted packet or "
1274                                                 "part has been ignored.");
1275                                 printed_ignore_warning = 1;
1276                         }
1277                         buffer = ((char *) buffer) + pkg_length;
1278                         continue;
1279                 }
1280 #endif /* HAVE_LIBGCRYPT */
1281                 else if (pkg_type == TYPE_SIGN_SHA256)
1282                 {
1283                         status = parse_part_sign_sha256 (se,
1284                                         &buffer, &buffer_size, flags);
1285                         if (status != 0)
1286                         {
1287                                 ERROR ("network plugin: Verifying HMAC-SHA-256 "
1288                                                 "signature failed "
1289                                                 "with status %i.", status);
1290                                 break;
1291                         }
1292                 }
1293 #if HAVE_LIBGCRYPT
1294                 else if ((se->data.server.security_level == SECURITY_LEVEL_SIGN)
1295                                 && (packet_was_encrypted == 0)
1296                                 && (packet_was_signed == 0))
1297                 {
1298                         if (printed_ignore_warning == 0)
1299                         {
1300                                 INFO ("network plugin: Unsigned packet or "
1301                                                 "part has been ignored.");
1302                                 printed_ignore_warning = 1;
1303                         }
1304                         buffer = ((char *) buffer) + pkg_length;
1305                         continue;
1306                 }
1307 #endif /* HAVE_LIBGCRYPT */
1308                 else if (pkg_type == TYPE_VALUES)
1309                 {
1310                         status = parse_part_values (&buffer, &buffer_size,
1311                                         &vl.values, &vl.values_len);
1312                         if (status != 0)
1313                                 break;
1314
1315                         network_dispatch_values (&vl);
1316
1317                         sfree (vl.values);
1318                 }
1319                 else if (pkg_type == TYPE_TIME)
1320                 {
1321                         uint64_t tmp = 0;
1322                         status = parse_part_number (&buffer, &buffer_size,
1323                                         &tmp);
1324                         if (status == 0)
1325                         {
1326                                 vl.time = (time_t) tmp;
1327                                 n.time = (time_t) tmp;
1328                         }
1329                 }
1330                 else if (pkg_type == TYPE_INTERVAL)
1331                 {
1332                         uint64_t tmp = 0;
1333                         status = parse_part_number (&buffer, &buffer_size,
1334                                         &tmp);
1335                         if (status == 0)
1336                                 vl.interval = (int) tmp;
1337                 }
1338                 else if (pkg_type == TYPE_HOST)
1339                 {
1340                         status = parse_part_string (&buffer, &buffer_size,
1341                                         vl.host, sizeof (vl.host));
1342                         if (status == 0)
1343                                 sstrncpy (n.host, vl.host, sizeof (n.host));
1344                 }
1345                 else if (pkg_type == TYPE_PLUGIN)
1346                 {
1347                         status = parse_part_string (&buffer, &buffer_size,
1348                                         vl.plugin, sizeof (vl.plugin));
1349                         if (status == 0)
1350                                 sstrncpy (n.plugin, vl.plugin,
1351                                                 sizeof (n.plugin));
1352                 }
1353                 else if (pkg_type == TYPE_PLUGIN_INSTANCE)
1354                 {
1355                         status = parse_part_string (&buffer, &buffer_size,
1356                                         vl.plugin_instance,
1357                                         sizeof (vl.plugin_instance));
1358                         if (status == 0)
1359                                 sstrncpy (n.plugin_instance,
1360                                                 vl.plugin_instance,
1361                                                 sizeof (n.plugin_instance));
1362                 }
1363                 else if (pkg_type == TYPE_TYPE)
1364                 {
1365                         status = parse_part_string (&buffer, &buffer_size,
1366                                         vl.type, sizeof (vl.type));
1367                         if (status == 0)
1368                                 sstrncpy (n.type, vl.type, sizeof (n.type));
1369                 }
1370                 else if (pkg_type == TYPE_TYPE_INSTANCE)
1371                 {
1372                         status = parse_part_string (&buffer, &buffer_size,
1373                                         vl.type_instance,
1374                                         sizeof (vl.type_instance));
1375                         if (status == 0)
1376                                 sstrncpy (n.type_instance, vl.type_instance,
1377                                                 sizeof (n.type_instance));
1378                 }
1379                 else if (pkg_type == TYPE_MESSAGE)
1380                 {
1381                         status = parse_part_string (&buffer, &buffer_size,
1382                                         n.message, sizeof (n.message));
1383
1384                         if (status != 0)
1385                         {
1386                                 /* do nothing */
1387                         }
1388                         else if ((n.severity != NOTIF_FAILURE)
1389                                         && (n.severity != NOTIF_WARNING)
1390                                         && (n.severity != NOTIF_OKAY))
1391                         {
1392                                 INFO ("network plugin: "
1393                                                 "Ignoring notification with "
1394                                                 "unknown severity %i.",
1395                                                 n.severity);
1396                         }
1397                         else if (n.time <= 0)
1398                         {
1399                                 INFO ("network plugin: "
1400                                                 "Ignoring notification with "
1401                                                 "time == 0.");
1402                         }
1403                         else if (strlen (n.message) <= 0)
1404                         {
1405                                 INFO ("network plugin: "
1406                                                 "Ignoring notification with "
1407                                                 "an empty message.");
1408                         }
1409                         else
1410                         {
1411                                 plugin_dispatch_notification (&n);
1412                         }
1413                 }
1414                 else if (pkg_type == TYPE_SEVERITY)
1415                 {
1416                         uint64_t tmp = 0;
1417                         status = parse_part_number (&buffer, &buffer_size,
1418                                         &tmp);
1419                         if (status == 0)
1420                                 n.severity = (int) tmp;
1421                 }
1422                 else
1423                 {
1424                         DEBUG ("network plugin: parse_packet: Unknown part"
1425                                         " type: 0x%04hx", pkg_type);
1426                         buffer = ((char *) buffer) + pkg_length;
1427                 }
1428         } /* while (buffer_size > sizeof (part_header_t)) */
1429
1430         if (status == 0 && buffer_size > 0)
1431                 WARNING ("network plugin: parse_packet: Received truncated "
1432                                 "packet, try increasing `MaxPacketSize'");
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->data);
1998       sfree (ent);
1999       continue;
2000     }
2001
2002     parse_packet (se, ent->data, ent->data_len, /* flags = */ 0);
2003     sfree (ent->data);
2004     sfree (ent);
2005   } /* while (42) */
2006
2007   return (NULL);
2008 } /* }}} void *dispatch_thread */
2009
2010 static int network_receive (void) /* {{{ */
2011 {
2012         char buffer[network_config_packet_size];
2013         int  buffer_len;
2014
2015         int i;
2016         int status;
2017
2018         receive_list_entry_t *private_list_head;
2019         receive_list_entry_t *private_list_tail;
2020
2021         assert (listen_sockets_num > 0);
2022
2023         private_list_head = NULL;
2024         private_list_tail = NULL;
2025
2026         while (listen_loop == 0)
2027         {
2028                 status = poll (listen_sockets_pollfd, listen_sockets_num, -1);
2029
2030                 if (status <= 0)
2031                 {
2032                         char errbuf[1024];
2033                         if (errno == EINTR)
2034                                 continue;
2035                         ERROR ("poll failed: %s",
2036                                         sstrerror (errno, errbuf, sizeof (errbuf)));
2037                         return (-1);
2038                 }
2039
2040                 for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
2041                 {
2042                         receive_list_entry_t *ent;
2043
2044                         if ((listen_sockets_pollfd[i].revents
2045                                                 & (POLLIN | POLLPRI)) == 0)
2046                                 continue;
2047                         status--;
2048
2049                         buffer_len = recv (listen_sockets_pollfd[i].fd,
2050                                         buffer, sizeof (buffer),
2051                                         0 /* no flags */);
2052                         if (buffer_len < 0)
2053                         {
2054                                 char errbuf[1024];
2055                                 ERROR ("recv failed: %s",
2056                                                 sstrerror (errno, errbuf,
2057                                                         sizeof (errbuf)));
2058                                 return (-1);
2059                         }
2060
2061                         /* TODO: Possible performance enhancement: Do not free
2062                          * these entries in the dispatch thread but put them in
2063                          * another list, so we don't have to allocate more and
2064                          * more of these structures. */
2065                         ent = malloc (sizeof (receive_list_entry_t));
2066                         if (ent == NULL)
2067                         {
2068                                 ERROR ("network plugin: malloc failed.");
2069                                 return (-1);
2070                         }
2071                         memset (ent, 0, sizeof (receive_list_entry_t));
2072                         ent->data = malloc (network_config_packet_size);
2073                         if (ent->data == NULL)
2074                         {
2075                                 ERROR ("network plugin: malloc failed.");
2076                                 return (-1);
2077                         }
2078                         ent->fd = listen_sockets_pollfd[i].fd;
2079                         ent->next = NULL;
2080
2081                         memcpy (ent->data, buffer, buffer_len);
2082                         ent->data_len = buffer_len;
2083
2084                         if (private_list_head == NULL)
2085                                 private_list_head = ent;
2086                         else
2087                                 private_list_tail->next = ent;
2088                         private_list_tail = ent;
2089
2090                         /* Do not block here. Blocking here has led to
2091                          * insufficient performance in the past. */
2092                         if (pthread_mutex_trylock (&receive_list_lock) == 0)
2093                         {
2094                                 if (receive_list_head == NULL)
2095                                         receive_list_head = private_list_head;
2096                                 else
2097                                         receive_list_tail->next = private_list_head;
2098                                 receive_list_tail = private_list_tail;
2099
2100                                 private_list_head = NULL;
2101                                 private_list_tail = NULL;
2102
2103                                 pthread_cond_signal (&receive_list_cond);
2104                                 pthread_mutex_unlock (&receive_list_lock);
2105                         }
2106                 } /* for (listen_sockets_pollfd) */
2107         } /* while (listen_loop == 0) */
2108
2109         /* Make sure everything is dispatched before exiting. */
2110         if (private_list_head != NULL)
2111         {
2112                 pthread_mutex_lock (&receive_list_lock);
2113
2114                 if (receive_list_head == NULL)
2115                         receive_list_head = private_list_head;
2116                 else
2117                         receive_list_tail->next = private_list_head;
2118                 receive_list_tail = private_list_tail;
2119
2120                 private_list_head = NULL;
2121                 private_list_tail = NULL;
2122
2123                 pthread_cond_signal (&receive_list_cond);
2124                 pthread_mutex_unlock (&receive_list_lock);
2125         }
2126
2127         return (0);
2128 } /* }}} int network_receive */
2129
2130 static void *receive_thread (void __attribute__((unused)) *arg)
2131 {
2132         return (network_receive () ? (void *) 1 : (void *) 0);
2133 } /* void *receive_thread */
2134
2135 static void network_init_buffer (void)
2136 {
2137         memset (send_buffer, 0, network_config_packet_size);
2138         send_buffer_ptr = send_buffer;
2139         send_buffer_fill = 0;
2140
2141         memset (&send_buffer_vl, 0, sizeof (send_buffer_vl));
2142 } /* int network_init_buffer */
2143
2144 static void networt_send_buffer_plain (const sockent_t *se, /* {{{ */
2145                 const char *buffer, size_t buffer_size)
2146 {
2147         int status;
2148
2149         while (42)
2150         {
2151                 status = sendto (se->data.client.fd, buffer, buffer_size,
2152                     /* flags = */ 0,
2153                     (struct sockaddr *) se->data.client.addr,
2154                     se->data.client.addrlen);
2155                 if (status < 0)
2156                 {
2157                         char errbuf[1024];
2158                         if (errno == EINTR)
2159                                 continue;
2160                         ERROR ("network plugin: sendto failed: %s",
2161                                         sstrerror (errno, errbuf,
2162                                                 sizeof (errbuf)));
2163                         break;
2164                 }
2165
2166                 break;
2167         } /* while (42) */
2168 } /* }}} void networt_send_buffer_plain */
2169
2170 #if HAVE_LIBGCRYPT
2171 #define BUFFER_ADD(p,s) do { \
2172   memcpy (buffer + buffer_offset, (p), (s)); \
2173   buffer_offset += (s); \
2174 } while (0)
2175
2176 static void networt_send_buffer_signed (const sockent_t *se, /* {{{ */
2177                 const char *in_buffer, size_t in_buffer_size)
2178 {
2179   part_signature_sha256_t ps;
2180   char buffer[BUFF_SIG_SIZE + in_buffer_size];
2181   size_t buffer_offset;
2182   size_t username_len;
2183
2184   gcry_md_hd_t hd;
2185   gcry_error_t err;
2186   unsigned char *hash;
2187
2188   hd = NULL;
2189   err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
2190   if (err != 0)
2191   {
2192     ERROR ("network plugin: Creating HMAC object failed: %s",
2193         gcry_strerror (err));
2194     return;
2195   }
2196
2197   err = gcry_md_setkey (hd, se->data.client.password,
2198       strlen (se->data.client.password));
2199   if (err != 0)
2200   {
2201     ERROR ("network plugin: gcry_md_setkey failed: %s",
2202         gcry_strerror (err));
2203     gcry_md_close (hd);
2204     return;
2205   }
2206
2207   username_len = strlen (se->data.client.username);
2208   if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE))
2209   {
2210     ERROR ("network plugin: Username too long: %s",
2211         se->data.client.username);
2212     return;
2213   }
2214
2215   memcpy (buffer + PART_SIGNATURE_SHA256_SIZE,
2216       se->data.client.username, username_len);
2217   memcpy (buffer + PART_SIGNATURE_SHA256_SIZE + username_len,
2218       in_buffer, in_buffer_size);
2219
2220   /* Initialize the `ps' structure. */
2221   memset (&ps, 0, sizeof (ps));
2222   ps.head.type = htons (TYPE_SIGN_SHA256);
2223   ps.head.length = htons (PART_SIGNATURE_SHA256_SIZE + username_len);
2224
2225   /* Calculate the hash value. */
2226   gcry_md_write (hd, buffer + PART_SIGNATURE_SHA256_SIZE,
2227       username_len + in_buffer_size);
2228   hash = gcry_md_read (hd, GCRY_MD_SHA256);
2229   if (hash == NULL)
2230   {
2231     ERROR ("network plugin: gcry_md_read failed.");
2232     gcry_md_close (hd);
2233     return;
2234   }
2235   memcpy (ps.hash, hash, sizeof (ps.hash));
2236
2237   /* Add the header */
2238   buffer_offset = 0;
2239
2240   BUFFER_ADD (&ps.head.type, sizeof (ps.head.type));
2241   BUFFER_ADD (&ps.head.length, sizeof (ps.head.length));
2242   BUFFER_ADD (ps.hash, sizeof (ps.hash));
2243
2244   assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
2245
2246   gcry_md_close (hd);
2247   hd = NULL;
2248
2249   buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
2250   networt_send_buffer_plain (se, buffer, buffer_offset);
2251 } /* }}} void networt_send_buffer_signed */
2252
2253 static void networt_send_buffer_encrypted (sockent_t *se, /* {{{ */
2254                 const char *in_buffer, size_t in_buffer_size)
2255 {
2256   part_encryption_aes256_t pea;
2257   char buffer[BUFF_SIG_SIZE + in_buffer_size];
2258   size_t buffer_size;
2259   size_t buffer_offset;
2260   size_t header_size;
2261   size_t username_len;
2262   gcry_error_t err;
2263   gcry_cipher_hd_t cypher;
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   DEBUG ("network plugin: networt_send_buffer_encrypted: "
2284       "buffer_size = %zu;", buffer_size);
2285
2286   pea.head.length = htons ((uint16_t) (PART_ENCRYPTION_AES256_SIZE
2287         + username_len + in_buffer_size));
2288   pea.username_length = htons ((uint16_t) username_len);
2289
2290   /* Chose a random initialization vector. */
2291   gcry_randomize ((void *) &pea.iv, sizeof (pea.iv), GCRY_STRONG_RANDOM);
2292
2293   /* Create hash of the payload */
2294   gcry_md_hash_buffer (GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
2295
2296   /* Initialize the buffer */
2297   buffer_offset = 0;
2298   memset (buffer, 0, sizeof (buffer));
2299
2300
2301   BUFFER_ADD (&pea.head.type, sizeof (pea.head.type));
2302   BUFFER_ADD (&pea.head.length, sizeof (pea.head.length));
2303   BUFFER_ADD (&pea.username_length, sizeof (pea.username_length));
2304   BUFFER_ADD (pea.username, username_len);
2305   BUFFER_ADD (pea.iv, sizeof (pea.iv));
2306   assert (buffer_offset == header_size);
2307   BUFFER_ADD (pea.hash, sizeof (pea.hash));
2308   BUFFER_ADD (in_buffer, in_buffer_size);
2309
2310   assert (buffer_offset == buffer_size);
2311
2312   cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
2313       se->data.client.password);
2314   if (cypher == NULL)
2315     return;
2316
2317   /* Encrypt the buffer in-place */
2318   err = gcry_cipher_encrypt (cypher,
2319       buffer      + header_size,
2320       buffer_size - header_size,
2321       /* in = */ NULL, /* in len = */ 0);
2322   if (err != 0)
2323   {
2324     ERROR ("network plugin: gcry_cipher_encrypt returned: %s",
2325         gcry_strerror (err));
2326     return;
2327   }
2328
2329   /* Send it out without further modifications */
2330   networt_send_buffer_plain (se, buffer, buffer_size);
2331 } /* }}} void networt_send_buffer_encrypted */
2332 #undef BUFFER_ADD
2333 #endif /* HAVE_LIBGCRYPT */
2334
2335 static void network_send_buffer (char *buffer, size_t buffer_len) /* {{{ */
2336 {
2337   sockent_t *se;
2338
2339   DEBUG ("network plugin: network_send_buffer: buffer_len = %zu", buffer_len);
2340
2341   for (se = sending_sockets; se != NULL; se = se->next)
2342   {
2343 #if HAVE_LIBGCRYPT
2344     if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
2345       networt_send_buffer_encrypted (se, buffer, buffer_len);
2346     else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
2347       networt_send_buffer_signed (se, buffer, buffer_len);
2348     else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
2349 #endif /* HAVE_LIBGCRYPT */
2350       networt_send_buffer_plain (se, buffer, buffer_len);
2351   } /* for (sending_sockets) */
2352 } /* }}} void network_send_buffer */
2353
2354 static int add_to_buffer (char *buffer, int buffer_size, /* {{{ */
2355                 value_list_t *vl_def,
2356                 const data_set_t *ds, const value_list_t *vl)
2357 {
2358         char *buffer_orig = buffer;
2359
2360         if (strcmp (vl_def->host, vl->host) != 0)
2361         {
2362                 if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
2363                                         vl->host, strlen (vl->host)) != 0)
2364                         return (-1);
2365                 sstrncpy (vl_def->host, vl->host, sizeof (vl_def->host));
2366         }
2367
2368         if (vl_def->time != vl->time)
2369         {
2370                 if (write_part_number (&buffer, &buffer_size, TYPE_TIME,
2371                                         (uint64_t) vl->time))
2372                         return (-1);
2373                 vl_def->time = vl->time;
2374         }
2375
2376         if (vl_def->interval != vl->interval)
2377         {
2378                 if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL,
2379                                         (uint64_t) vl->interval))
2380                         return (-1);
2381                 vl_def->interval = vl->interval;
2382         }
2383
2384         if (strcmp (vl_def->plugin, vl->plugin) != 0)
2385         {
2386                 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
2387                                         vl->plugin, strlen (vl->plugin)) != 0)
2388                         return (-1);
2389                 sstrncpy (vl_def->plugin, vl->plugin, sizeof (vl_def->plugin));
2390         }
2391
2392         if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
2393         {
2394                 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
2395                                         vl->plugin_instance,
2396                                         strlen (vl->plugin_instance)) != 0)
2397                         return (-1);
2398                 sstrncpy (vl_def->plugin_instance, vl->plugin_instance, sizeof (vl_def->plugin_instance));
2399         }
2400
2401         if (strcmp (vl_def->type, vl->type) != 0)
2402         {
2403                 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
2404                                         vl->type, strlen (vl->type)) != 0)
2405                         return (-1);
2406                 sstrncpy (vl_def->type, ds->type, sizeof (vl_def->type));
2407         }
2408
2409         if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
2410         {
2411                 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
2412                                         vl->type_instance,
2413                                         strlen (vl->type_instance)) != 0)
2414                         return (-1);
2415                 sstrncpy (vl_def->type_instance, vl->type_instance, sizeof (vl_def->type_instance));
2416         }
2417         
2418         if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
2419                 return (-1);
2420
2421         return (buffer - buffer_orig);
2422 } /* }}} int add_to_buffer */
2423
2424 static void flush_buffer (void)
2425 {
2426         DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
2427                         send_buffer_fill);
2428
2429         network_send_buffer (send_buffer, (size_t) send_buffer_fill);
2430         network_init_buffer ();
2431 }
2432
2433 static int network_write (const data_set_t *ds, const value_list_t *vl,
2434                 user_data_t __attribute__((unused)) *user_data)
2435 {
2436         int status;
2437
2438         if (!check_send_okay (vl))
2439         {
2440 #if COLLECT_DEBUG
2441           char name[6*DATA_MAX_NAME_LEN];
2442           FORMAT_VL (name, sizeof (name), vl);
2443           name[sizeof (name) - 1] = 0;
2444           DEBUG ("network plugin: network_write: "
2445               "NOT sending %s.", name);
2446 #endif
2447           return (0);
2448         }
2449
2450         uc_meta_data_add_unsigned_int (vl,
2451             "network:time_sent", (uint64_t) vl->time);
2452
2453         pthread_mutex_lock (&send_buffer_lock);
2454
2455         status = add_to_buffer (send_buffer_ptr,
2456                         network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2457                         &send_buffer_vl,
2458                         ds, vl);
2459         if (status >= 0)
2460         {
2461                 /* status == bytes added to the buffer */
2462                 send_buffer_fill += status;
2463                 send_buffer_ptr  += status;
2464         }
2465         else
2466         {
2467                 flush_buffer ();
2468
2469                 status = add_to_buffer (send_buffer_ptr,
2470                                 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2471                                 &send_buffer_vl,
2472                                 ds, vl);
2473
2474                 if (status >= 0)
2475                 {
2476                         send_buffer_fill += status;
2477                         send_buffer_ptr  += status;
2478                 }
2479         }
2480
2481         if (status < 0)
2482         {
2483                 ERROR ("network plugin: Unable to append to the "
2484                                 "buffer for some weird reason");
2485         }
2486         else if ((network_config_packet_size - send_buffer_fill) < 15)
2487         {
2488                 flush_buffer ();
2489         }
2490
2491         pthread_mutex_unlock (&send_buffer_lock);
2492
2493         return ((status < 0) ? -1 : 0);
2494 } /* int network_write */
2495
2496 static int network_config_set_boolean (const oconfig_item_t *ci, /* {{{ */
2497     int *retval)
2498 {
2499   if ((ci->values_num != 1)
2500       || ((ci->values[0].type != OCONFIG_TYPE_BOOLEAN)
2501         && (ci->values[0].type != OCONFIG_TYPE_STRING)))
2502   {
2503     ERROR ("network plugin: The `%s' config option needs "
2504         "exactly one boolean argument.", ci->key);
2505     return (-1);
2506   }
2507
2508   if (ci->values[0].type == OCONFIG_TYPE_BOOLEAN)
2509   {
2510     if (ci->values[0].value.boolean)
2511       *retval = 1;
2512     else
2513       *retval = 0;
2514   }
2515   else
2516   {
2517     char *str = ci->values[0].value.string;
2518
2519     if ((strcasecmp ("true", str) == 0)
2520         || (strcasecmp ("yes", str) == 0)
2521         || (strcasecmp ("on", str) == 0))
2522       *retval = 1;
2523     else if ((strcasecmp ("false", str) == 0)
2524         || (strcasecmp ("no", str) == 0)
2525         || (strcasecmp ("off", str) == 0))
2526       *retval = 0;
2527     else
2528     {
2529       ERROR ("network plugin: Cannot parse string value `%s' of the `%s' "
2530           "option as boolean value.",
2531           str, ci->key);
2532       return (-1);
2533     }
2534   }
2535
2536   return (0);
2537 } /* }}} int network_config_set_boolean */
2538
2539 static int network_config_set_ttl (const oconfig_item_t *ci) /* {{{ */
2540 {
2541   int tmp;
2542   if ((ci->values_num != 1)
2543       || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2544   {
2545     WARNING ("network plugin: The `TimeToLive' config option needs exactly "
2546         "one numeric argument.");
2547     return (-1);
2548   }
2549
2550   tmp = (int) ci->values[0].value.number;
2551   if ((tmp > 0) && (tmp <= 255))
2552     network_config_ttl = tmp;
2553
2554   return (0);
2555 } /* }}} int network_config_set_ttl */
2556
2557 static int network_config_set_buffer_size (const oconfig_item_t *ci) /* {{{ */
2558 {
2559   int tmp;
2560   if ((ci->values_num != 1)
2561       || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2562   {
2563     WARNING ("network plugin: The `MaxPacketSize' config option needs exactly "
2564         "one numeric argument.");
2565     return (-1);
2566   }
2567
2568   tmp = (int) ci->values[0].value.number;
2569   if ((tmp >= 1024) && (tmp <= 65535))
2570     network_config_packet_size = tmp;
2571
2572   return (0);
2573 } /* }}} int network_config_set_buffer_size */
2574
2575 #if HAVE_LIBGCRYPT
2576 static int network_config_set_string (const oconfig_item_t *ci, /* {{{ */
2577     char **ret_string)
2578 {
2579   char *tmp;
2580   if ((ci->values_num != 1)
2581       || (ci->values[0].type != OCONFIG_TYPE_STRING))
2582   {
2583     WARNING ("network plugin: The `%s' config option needs exactly "
2584         "one string argument.", ci->key);
2585     return (-1);
2586   }
2587
2588   tmp = strdup (ci->values[0].value.string);
2589   if (tmp == NULL)
2590     return (-1);
2591
2592   sfree (*ret_string);
2593   *ret_string = tmp;
2594
2595   return (0);
2596 } /* }}} int network_config_set_string */
2597 #endif /* HAVE_LIBGCRYPT */
2598
2599 #if HAVE_LIBGCRYPT
2600 static int network_config_set_security_level (oconfig_item_t *ci, /* {{{ */
2601     int *retval)
2602 {
2603   char *str;
2604   if ((ci->values_num != 1)
2605       || (ci->values[0].type != OCONFIG_TYPE_STRING))
2606   {
2607     WARNING ("network plugin: The `SecurityLevel' config option needs exactly "
2608         "one string argument.");
2609     return (-1);
2610   }
2611
2612   str = ci->values[0].value.string;
2613   if (strcasecmp ("Encrypt", str) == 0)
2614     *retval = SECURITY_LEVEL_ENCRYPT;
2615   else if (strcasecmp ("Sign", str) == 0)
2616     *retval = SECURITY_LEVEL_SIGN;
2617   else if (strcasecmp ("None", str) == 0)
2618     *retval = SECURITY_LEVEL_NONE;
2619   else
2620   {
2621     WARNING ("network plugin: Unknown security level: %s.", str);
2622     return (-1);
2623   }
2624
2625   return (0);
2626 } /* }}} int network_config_set_security_level */
2627 #endif /* HAVE_LIBGCRYPT */
2628
2629 static int network_config_add_listen (const oconfig_item_t *ci) /* {{{ */
2630 {
2631   sockent_t *se;
2632   int status;
2633   int i;
2634
2635   if ((ci->values_num < 1) || (ci->values_num > 2)
2636       || (ci->values[0].type != OCONFIG_TYPE_STRING)
2637       || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
2638   {
2639     ERROR ("network plugin: The `%s' config option needs "
2640         "one or two string arguments.", ci->key);
2641     return (-1);
2642   }
2643
2644   se = malloc (sizeof (*se));
2645   if (se == NULL)
2646   {
2647     ERROR ("network plugin: malloc failed.");
2648     return (-1);
2649   }
2650   sockent_init (se, SOCKENT_TYPE_SERVER);
2651
2652   se->node = strdup (ci->values[0].value.string);
2653   if (ci->values_num >= 2)
2654     se->service = strdup (ci->values[1].value.string);
2655
2656   for (i = 0; i < ci->children_num; i++)
2657   {
2658     oconfig_item_t *child = ci->children + i;
2659
2660 #if HAVE_LIBGCRYPT
2661     if (strcasecmp ("AuthFile", child->key) == 0)
2662       network_config_set_string (child, &se->data.server.auth_file);
2663     else if (strcasecmp ("SecurityLevel", child->key) == 0)
2664       network_config_set_security_level (child,
2665           &se->data.server.security_level);
2666     else
2667 #endif /* HAVE_LIBGCRYPT */
2668     {
2669       WARNING ("network plugin: Option `%s' is not allowed here.",
2670           child->key);
2671     }
2672   }
2673
2674 #if HAVE_LIBGCRYPT
2675   if ((se->data.server.security_level > SECURITY_LEVEL_NONE)
2676       && (se->data.server.auth_file == NULL))
2677   {
2678     ERROR ("network plugin: A security level higher than `none' was "
2679         "requested, but no AuthFile option was given. Cowardly refusing to "
2680         "open this socket!");
2681     sockent_destroy (se);
2682     return (-1);
2683   }
2684 #endif /* HAVE_LIBGCRYPT */
2685
2686   status = sockent_open (se);
2687   if (status != 0)
2688   {
2689     ERROR ("network plugin: network_config_add_listen: sockent_open failed.");
2690     sockent_destroy (se);
2691     return (-1);
2692   }
2693
2694   status = sockent_add (se);
2695   if (status != 0)
2696   {
2697     ERROR ("network plugin: network_config_add_listen: sockent_add failed.");
2698     sockent_destroy (se);
2699     return (-1);
2700   }
2701
2702   return (0);
2703 } /* }}} int network_config_add_listen */
2704
2705 static int network_config_add_server (const oconfig_item_t *ci) /* {{{ */
2706 {
2707   sockent_t *se;
2708   int status;
2709   int i;
2710
2711   if ((ci->values_num < 1) || (ci->values_num > 2)
2712       || (ci->values[0].type != OCONFIG_TYPE_STRING)
2713       || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
2714   {
2715     ERROR ("network plugin: The `%s' config option needs "
2716         "one or two string arguments.", ci->key);
2717     return (-1);
2718   }
2719
2720   se = malloc (sizeof (*se));
2721   if (se == NULL)
2722   {
2723     ERROR ("network plugin: malloc failed.");
2724     return (-1);
2725   }
2726   sockent_init (se, SOCKENT_TYPE_CLIENT);
2727
2728   se->node = strdup (ci->values[0].value.string);
2729   if (ci->values_num >= 2)
2730     se->service = strdup (ci->values[1].value.string);
2731
2732   for (i = 0; i < ci->children_num; i++)
2733   {
2734     oconfig_item_t *child = ci->children + i;
2735
2736 #if HAVE_LIBGCRYPT
2737     if (strcasecmp ("Username", child->key) == 0)
2738       network_config_set_string (child, &se->data.client.username);
2739     else if (strcasecmp ("Password", child->key) == 0)
2740       network_config_set_string (child, &se->data.client.password);
2741     else if (strcasecmp ("SecurityLevel", child->key) == 0)
2742       network_config_set_security_level (child,
2743           &se->data.client.security_level);
2744     else
2745 #endif /* HAVE_LIBGCRYPT */
2746     {
2747       WARNING ("network plugin: Option `%s' is not allowed here.",
2748           child->key);
2749     }
2750   }
2751
2752 #if HAVE_LIBGCRYPT
2753   if ((se->data.client.security_level > SECURITY_LEVEL_NONE)
2754       && ((se->data.client.username == NULL)
2755         || (se->data.client.password == NULL)))
2756   {
2757     ERROR ("network plugin: A security level higher than `none' was "
2758         "requested, but no Username or Password option was given. "
2759         "Cowardly refusing to open this socket!");
2760     sockent_destroy (se);
2761     return (-1);
2762   }
2763 #endif /* HAVE_LIBGCRYPT */
2764
2765   status = sockent_open (se);
2766   if (status != 0)
2767   {
2768     ERROR ("network plugin: network_config_add_server: sockent_open failed.");
2769     sockent_destroy (se);
2770     return (-1);
2771   }
2772
2773   status = sockent_add (se);
2774   if (status != 0)
2775   {
2776     ERROR ("network plugin: network_config_add_server: sockent_add failed.");
2777     sockent_destroy (se);
2778     return (-1);
2779   }
2780
2781   return (0);
2782 } /* }}} int network_config_add_server */
2783
2784 static int network_config (oconfig_item_t *ci) /* {{{ */
2785 {
2786   int i;
2787
2788   for (i = 0; i < ci->children_num; i++)
2789   {
2790     oconfig_item_t *child = ci->children + i;
2791
2792     if (strcasecmp ("Listen", child->key) == 0)
2793       network_config_add_listen (child);
2794     else if (strcasecmp ("Server", child->key) == 0)
2795       network_config_add_server (child);
2796     else if (strcasecmp ("TimeToLive", child->key) == 0)
2797       network_config_set_ttl (child);
2798     else if (strcasecmp ("MaxPacketSize", child->key) == 0)
2799       network_config_set_buffer_size (child);
2800     else if (strcasecmp ("Forward", child->key) == 0)
2801       network_config_set_boolean (child, &network_config_forward);
2802     else if (strcasecmp ("CacheFlush", child->key) == 0)
2803       /* no op for backwards compatibility only */;
2804     else
2805     {
2806       WARNING ("network plugin: Option `%s' is not allowed here.",
2807           child->key);
2808     }
2809   }
2810
2811   return (0);
2812 } /* }}} int network_config */
2813
2814 static int network_notification (const notification_t *n,
2815                 user_data_t __attribute__((unused)) *user_data)
2816 {
2817   char  buffer[network_config_packet_size];
2818   char *buffer_ptr = buffer;
2819   int   buffer_free = sizeof (buffer);
2820   int   status;
2821
2822   memset (buffer, '\0', sizeof (buffer));
2823
2824
2825   status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME,
2826       (uint64_t) n->time);
2827   if (status != 0)
2828     return (-1);
2829
2830   status = write_part_number (&buffer_ptr, &buffer_free, TYPE_SEVERITY,
2831       (uint64_t) n->severity);
2832   if (status != 0)
2833     return (-1);
2834
2835   if (strlen (n->host) > 0)
2836   {
2837     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_HOST,
2838         n->host, strlen (n->host));
2839     if (status != 0)
2840       return (-1);
2841   }
2842
2843   if (strlen (n->plugin) > 0)
2844   {
2845     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_PLUGIN,
2846         n->plugin, strlen (n->plugin));
2847     if (status != 0)
2848       return (-1);
2849   }
2850
2851   if (strlen (n->plugin_instance) > 0)
2852   {
2853     status = write_part_string (&buffer_ptr, &buffer_free,
2854         TYPE_PLUGIN_INSTANCE,
2855         n->plugin_instance, strlen (n->plugin_instance));
2856     if (status != 0)
2857       return (-1);
2858   }
2859
2860   if (strlen (n->type) > 0)
2861   {
2862     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE,
2863         n->type, strlen (n->type));
2864     if (status != 0)
2865       return (-1);
2866   }
2867
2868   if (strlen (n->type_instance) > 0)
2869   {
2870     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
2871         n->type_instance, strlen (n->type_instance));
2872     if (status != 0)
2873       return (-1);
2874   }
2875
2876   status = write_part_string (&buffer_ptr, &buffer_free, TYPE_MESSAGE,
2877       n->message, strlen (n->message));
2878   if (status != 0)
2879     return (-1);
2880
2881   network_send_buffer (buffer, sizeof (buffer) - buffer_free);
2882
2883   return (0);
2884 } /* int network_notification */
2885
2886 static int network_shutdown (void)
2887 {
2888         listen_loop++;
2889
2890         /* Kill the listening thread */
2891         if (receive_thread_running != 0)
2892         {
2893                 INFO ("network plugin: Stopping receive thread.");
2894                 pthread_kill (receive_thread_id, SIGTERM);
2895                 pthread_join (receive_thread_id, NULL /* no return value */);
2896                 memset (&receive_thread_id, 0, sizeof (receive_thread_id));
2897                 receive_thread_running = 0;
2898         }
2899
2900         /* Shutdown the dispatching thread */
2901         if (dispatch_thread_running != 0)
2902         {
2903                 INFO ("network plugin: Stopping dispatch thread.");
2904                 pthread_mutex_lock (&receive_list_lock);
2905                 pthread_cond_broadcast (&receive_list_cond);
2906                 pthread_mutex_unlock (&receive_list_lock);
2907                 pthread_join (dispatch_thread_id, /* ret = */ NULL);
2908                 dispatch_thread_running = 0;
2909         }
2910
2911         sockent_destroy (listen_sockets);
2912
2913         if (send_buffer_fill > 0)
2914                 flush_buffer ();
2915
2916         sfree (send_buffer);
2917
2918         /* TODO: Close `sending_sockets' */
2919
2920         plugin_unregister_config ("network");
2921         plugin_unregister_init ("network");
2922         plugin_unregister_write ("network");
2923         plugin_unregister_shutdown ("network");
2924
2925         return (0);
2926 } /* int network_shutdown */
2927
2928 static int network_init (void)
2929 {
2930         static _Bool have_init = false;
2931
2932         /* Check if we were already initialized. If so, just return - there's
2933          * nothing more to do (for now, that is). */
2934         if (have_init)
2935                 return (0);
2936         have_init = true;
2937
2938 #if HAVE_LIBGCRYPT
2939         gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
2940         gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
2941         gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
2942 #endif
2943
2944         plugin_register_shutdown ("network", network_shutdown);
2945
2946         send_buffer = malloc (network_config_packet_size);
2947         if (send_buffer == NULL)
2948         {
2949                 ERROR ("network plugin: malloc failed.");
2950                 return (-1);
2951         }
2952         network_init_buffer ();
2953
2954         /* setup socket(s) and so on */
2955         if (sending_sockets != NULL)
2956         {
2957                 plugin_register_write ("network", network_write,
2958                                 /* user_data = */ NULL);
2959                 plugin_register_notification ("network", network_notification,
2960                                 /* user_data = */ NULL);
2961         }
2962
2963         /* If no threads need to be started, return here. */
2964         if ((listen_sockets_num == 0)
2965                         || ((dispatch_thread_running != 0)
2966                                 && (receive_thread_running != 0)))
2967                 return (0);
2968
2969         if (dispatch_thread_running == 0)
2970         {
2971                 int status;
2972                 status = pthread_create (&dispatch_thread_id,
2973                                 NULL /* no attributes */,
2974                                 dispatch_thread,
2975                                 NULL /* no argument */);
2976                 if (status != 0)
2977                 {
2978                         char errbuf[1024];
2979                         ERROR ("network: pthread_create failed: %s",
2980                                         sstrerror (errno, errbuf,
2981                                                 sizeof (errbuf)));
2982                 }
2983                 else
2984                 {
2985                         dispatch_thread_running = 1;
2986                 }
2987         }
2988
2989         if (receive_thread_running == 0)
2990         {
2991                 int status;
2992                 status = pthread_create (&receive_thread_id,
2993                                 NULL /* no attributes */,
2994                                 receive_thread,
2995                                 NULL /* no argument */);
2996                 if (status != 0)
2997                 {
2998                         char errbuf[1024];
2999                         ERROR ("network: pthread_create failed: %s",
3000                                         sstrerror (errno, errbuf,
3001                                                 sizeof (errbuf)));
3002                 }
3003                 else
3004                 {
3005                         receive_thread_running = 1;
3006                 }
3007         }
3008
3009         return (0);
3010 } /* int network_init */
3011
3012 /* 
3013  * The flush option of the network plugin cannot flush individual identifiers.
3014  * All the values are added to a buffer and sent when the buffer is full, the
3015  * requested value may or may not be in there, it's not worth finding out. We
3016  * just send the buffer if `flush'  is called - if the requested value was in
3017  * there, good. If not, well, then there is nothing to flush.. -octo
3018  */
3019 static int network_flush (int timeout,
3020                 const char __attribute__((unused)) *identifier,
3021                 user_data_t __attribute__((unused)) *user_data)
3022 {
3023         pthread_mutex_lock (&send_buffer_lock);
3024
3025         if (send_buffer_fill > 0)
3026           flush_buffer ();
3027
3028         pthread_mutex_unlock (&send_buffer_lock);
3029
3030         return (0);
3031 } /* int network_flush */
3032
3033 void module_register (void)
3034 {
3035         plugin_register_complex_config ("network", network_config);
3036         plugin_register_init   ("network", network_init);
3037         plugin_register_flush   ("network", network_flush,
3038                         /* user_data = */ NULL);
3039 } /* void module_register */
3040
3041 /* vim: set fdm=marker : */