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