network plugin: Add MaxPacketSize config option to the network plugin.
[collectd.git] / src / network.c
1 /**
2  * collectd - src/network.c
3  * Copyright (C) 2005-2009  Florian octo Forster
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Authors:
19  *   Florian octo Forster <octo at verplant.org>
20  **/
21
22 #define _BSD_SOURCE /* For struct ip_mreq */
23
24 #include "collectd.h"
25 #include "plugin.h"
26 #include "common.h"
27 #include "configfile.h"
28 #include "utils_fbhash.h"
29 #include "utils_avltree.h"
30 #include "utils_cache.h"
31
32 #include "network.h"
33
34 #if HAVE_PTHREAD_H
35 # include <pthread.h>
36 #endif
37 #if HAVE_SYS_SOCKET_H
38 # include <sys/socket.h>
39 #endif
40 #if HAVE_NETDB_H
41 # include <netdb.h>
42 #endif
43 #if HAVE_NETINET_IN_H
44 # include <netinet/in.h>
45 #endif
46 #if HAVE_ARPA_INET_H
47 # include <arpa/inet.h>
48 #endif
49 #if HAVE_POLL_H
50 # include <poll.h>
51 #endif
52
53 #if HAVE_LIBGCRYPT
54 # include <gcrypt.h>
55 #endif
56
57 #ifndef IPV6_ADD_MEMBERSHIP
58 # ifdef IPV6_JOIN_GROUP
59 #  define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
60 # else
61 #  error "Neither IP_ADD_MEMBERSHIP nor IPV6_JOIN_GROUP is defined"
62 # endif
63 #endif /* !IP_ADD_MEMBERSHIP */
64
65 /*
66  * Maximum size required for encryption / signing:
67  *
68  *    42 bytes for the encryption header
69  * +  64 bytes for the username
70  * -----------
71  * = 106 bytes
72  */
73 #define BUFF_SIG_SIZE 106
74
75 /*
76  * Private data types
77  */
78 #define SECURITY_LEVEL_NONE     0
79 #if HAVE_LIBGCRYPT
80 # define SECURITY_LEVEL_SIGN    1
81 # define SECURITY_LEVEL_ENCRYPT 2
82 #endif
83 struct sockent_client
84 {
85         int fd;
86         struct sockaddr_storage *addr;
87         socklen_t                addrlen;
88 #if HAVE_LIBGCRYPT
89         int security_level;
90         char *username;
91         char *password;
92         gcry_cipher_hd_t cypher;
93         unsigned char password_hash[32];
94 #endif
95 };
96
97 struct sockent_server
98 {
99         int *fd;
100         size_t fd_num;
101 #if HAVE_LIBGCRYPT
102         int security_level;
103         char *auth_file;
104         fbhash_t *userdb;
105         gcry_cipher_hd_t cypher;
106 #endif
107 };
108
109 typedef struct sockent
110 {
111 #define SOCKENT_TYPE_CLIENT 1
112 #define SOCKENT_TYPE_SERVER 2
113         int type;
114
115         char *node;
116         char *service;
117
118         union
119         {
120                 struct sockent_client client;
121                 struct sockent_server server;
122         } data;
123
124         struct sockent *next;
125 } sockent_t;
126
127 /*                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
128  *  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
129  * +-------+-----------------------+-------------------------------+
130  * ! Ver.  !                       ! Length                        !
131  * +-------+-----------------------+-------------------------------+
132  */
133 struct part_header_s
134 {
135         uint16_t type;
136         uint16_t length;
137 };
138 typedef struct part_header_s part_header_t;
139
140 /*                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
141  *  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
142  * +-------------------------------+-------------------------------+
143  * ! Type                          ! Length                        !
144  * +-------------------------------+-------------------------------+
145  * : (Length - 4) Bytes                                            :
146  * +---------------------------------------------------------------+
147  */
148 struct part_string_s
149 {
150         part_header_t *head;
151         char *value;
152 };
153 typedef struct part_string_s part_string_t;
154
155 /*                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
156  *  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
157  * +-------------------------------+-------------------------------+
158  * ! Type                          ! Length                        !
159  * +-------------------------------+-------------------------------+
160  * : (Length - 4 == 2 || 4 || 8) Bytes                             :
161  * +---------------------------------------------------------------+
162  */
163 struct part_number_s
164 {
165         part_header_t *head;
166         uint64_t *value;
167 };
168 typedef struct part_number_s part_number_t;
169
170 /*                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
171  *  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
172  * +-------------------------------+-------------------------------+
173  * ! Type                          ! Length                        !
174  * +-------------------------------+---------------+---------------+
175  * ! Num of values                 ! Type0         ! Type1         !
176  * +-------------------------------+---------------+---------------+
177  * ! Value0                                                        !
178  * !                                                               !
179  * +---------------------------------------------------------------+
180  * ! Value1                                                        !
181  * !                                                               !
182  * +---------------------------------------------------------------+
183  */
184 struct part_values_s
185 {
186         part_header_t *head;
187         uint16_t *num_values;
188         uint8_t  *values_types;
189         value_t  *values;
190 };
191 typedef struct part_values_s part_values_t;
192
193 /*                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
194  *  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
195  * +-------------------------------+-------------------------------+
196  * ! Type                          ! Length                        !
197  * +-------------------------------+-------------------------------+
198  * ! Hash (Bits   0 -  31)                                         !
199  * : :                                                             :
200  * ! Hash (Bits 224 - 255)                                         !
201  * +---------------------------------------------------------------+
202  */
203 /* Minimum size */
204 #define PART_SIGNATURE_SHA256_SIZE 36
205 struct part_signature_sha256_s
206 {
207   part_header_t head;
208   unsigned char hash[32];
209   char *username;
210 };
211 typedef struct part_signature_sha256_s part_signature_sha256_t;
212
213 /*                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
214  *  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
215  * +-------------------------------+-------------------------------+
216  * ! Type                          ! Length                        !
217  * +-------------------------------+-------------------------------+
218  * ! Original length               ! Padding (0 - 15 bytes)        !
219  * +-------------------------------+-------------------------------+
220  * ! Hash (Bits   0 -  31)                                         !
221  * : :                                                             :
222  * ! Hash (Bits 128 - 159)                                         !
223  * +---------------------------------------------------------------+
224  */
225 /* Minimum size */
226 #define PART_ENCRYPTION_AES256_SIZE 42
227 struct part_encryption_aes256_s
228 {
229   part_header_t head;
230   uint16_t username_length;
231   char *username;
232   unsigned char iv[16];
233   /* <encrypted> */
234   unsigned char hash[20];
235   /*   <payload /> */
236   /* </encrypted> */
237 };
238 typedef struct part_encryption_aes256_s part_encryption_aes256_t;
239
240 struct receive_list_entry_s
241 {
242   char *data;
243   int  data_len;
244   int  fd;
245   struct receive_list_entry_s *next;
246 };
247 typedef struct receive_list_entry_s receive_list_entry_t;
248
249 /*
250  * Private variables
251  */
252 static int network_config_ttl = 0;
253 static size_t network_config_packet_size = 1024;
254 static int network_config_forward = 0;
255
256 static sockent_t *sending_sockets = NULL;
257
258 static receive_list_entry_t *receive_list_head = NULL;
259 static receive_list_entry_t *receive_list_tail = NULL;
260 static pthread_mutex_t       receive_list_lock = PTHREAD_MUTEX_INITIALIZER;
261 static pthread_cond_t        receive_list_cond = PTHREAD_COND_INITIALIZER;
262
263 static sockent_t     *listen_sockets = NULL;
264 static struct pollfd *listen_sockets_pollfd = NULL;
265 static size_t         listen_sockets_num = 0;
266
267 /* The receive and dispatch threads will run as long as `listen_loop' is set to
268  * zero. */
269 static int       listen_loop = 0;
270 static int       receive_thread_running = 0;
271 static pthread_t receive_thread_id;
272 static int       dispatch_thread_running = 0;
273 static pthread_t dispatch_thread_id;
274
275 /* Buffer in which to-be-sent network packets are constructed. */
276 static char            *send_buffer;
277 static char            *send_buffer_ptr;
278 static int              send_buffer_fill;
279 static value_list_t     send_buffer_vl = VALUE_LIST_STATIC;
280 static pthread_mutex_t  send_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
281
282 /*
283  * Private functions
284  */
285 static _Bool check_receive_okay (const value_list_t *vl) /* {{{ */
286 {
287   uint64_t time_sent = 0;
288   int status;
289
290   status = uc_meta_data_get_unsigned_int (vl,
291       "network:time_sent", &time_sent);
292
293   /* This is a value we already sent. Don't allow it to be received again in
294    * order to avoid looping. */
295   if ((status == 0) && (time_sent >= ((uint64_t) vl->time)))
296     return (false);
297
298   return (true);
299 } /* }}} _Bool check_receive_okay */
300
301 static _Bool check_send_okay (const value_list_t *vl) /* {{{ */
302 {
303   _Bool received = false;
304   int status;
305
306   if (network_config_forward != 0)
307     return (true);
308
309   if (vl->meta == NULL)
310     return (true);
311
312   status = meta_data_get_boolean (vl->meta, "network:received", &received);
313   if (status == -ENOENT)
314     return (true);
315   else if (status != 0)
316   {
317     ERROR ("network plugin: check_send_okay: meta_data_get_boolean failed "
318         "with status %i.", status);
319     return (true);
320   }
321
322   /* By default, only *send* value lists that were not *received* by the
323    * network plugin. */
324   return (!received);
325 } /* }}} _Bool check_send_okay */
326
327 static int network_dispatch_values (value_list_t *vl) /* {{{ */
328 {
329   int status;
330
331   if ((vl->time <= 0)
332       || (strlen (vl->host) <= 0)
333       || (strlen (vl->plugin) <= 0)
334       || (strlen (vl->type) <= 0))
335     return (-EINVAL);
336
337   if (!check_receive_okay (vl))
338   {
339 #if COLLECT_DEBUG
340           char name[6*DATA_MAX_NAME_LEN];
341           FORMAT_VL (name, sizeof (name), vl);
342           name[sizeof (name) - 1] = 0;
343           DEBUG ("network plugin: network_dispatch_values: "
344               "NOT dispatching %s.", name);
345 #endif
346     return (0);
347   }
348
349   assert (vl->meta == NULL);
350
351   vl->meta = meta_data_create ();
352   if (vl->meta == NULL)
353   {
354     ERROR ("network plugin: meta_data_create failed.");
355     return (-ENOMEM);
356   }
357
358   status = meta_data_add_boolean (vl->meta, "network:received", true);
359   if (status != 0)
360   {
361     ERROR ("network plugin: meta_data_add_boolean failed.");
362     meta_data_destroy (vl->meta);
363     vl->meta = NULL;
364     return (status);
365   }
366
367   plugin_dispatch_values (vl);
368
369   meta_data_destroy (vl->meta);
370   vl->meta = NULL;
371
372   return (0);
373 } /* }}} int network_dispatch_values */
374
375 #if HAVE_LIBGCRYPT
376 static gcry_cipher_hd_t network_get_aes256_cypher (sockent_t *se, /* {{{ */
377     const void *iv, size_t iv_size, const char *username)
378 {
379   gcry_error_t err;
380   gcry_cipher_hd_t *cyper_ptr;
381   unsigned char password_hash[32];
382
383   if (se->type == SOCKENT_TYPE_CLIENT)
384   {
385           cyper_ptr = &se->data.client.cypher;
386           memcpy (password_hash, se->data.client.password_hash,
387                           sizeof (password_hash));
388   }
389   else
390   {
391           char *secret;
392
393           cyper_ptr = &se->data.server.cypher;
394
395           if (username == NULL)
396                   return (NULL);
397
398           secret = fbh_get (se->data.server.userdb, username);
399           if (secret == NULL)
400                   return (NULL);
401
402           gcry_md_hash_buffer (GCRY_MD_SHA256,
403                           password_hash,
404                           secret, strlen (secret));
405
406           sfree (secret);
407   }
408
409   if (*cyper_ptr == NULL)
410   {
411     err = gcry_cipher_open (cyper_ptr,
412         GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB, /* flags = */ 0);
413     if (err != 0)
414     {
415       ERROR ("network plugin: gcry_cipher_open returned: %s",
416           gcry_strerror (err));
417       *cyper_ptr = NULL;
418       return (NULL);
419     }
420   }
421   else
422   {
423     gcry_cipher_reset (*cyper_ptr);
424   }
425   assert (*cyper_ptr != NULL);
426
427   err = gcry_cipher_setkey (*cyper_ptr,
428       password_hash, sizeof (password_hash));
429   if (err != 0)
430   {
431     ERROR ("network plugin: gcry_cipher_setkey returned: %s",
432         gcry_strerror (err));
433     gcry_cipher_close (*cyper_ptr);
434     *cyper_ptr = NULL;
435     return (NULL);
436   }
437
438   err = gcry_cipher_setiv (*cyper_ptr, iv, iv_size);
439   if (err != 0)
440   {
441     ERROR ("network plugin: gcry_cipher_setkey returned: %s",
442         gcry_strerror (err));
443     gcry_cipher_close (*cyper_ptr);
444     *cyper_ptr = NULL;
445     return (NULL);
446   }
447
448   return (*cyper_ptr);
449 } /* }}} int network_get_aes256_cypher */
450 #endif /* HAVE_LIBGCRYPT */
451
452 static int write_part_values (char **ret_buffer, int *ret_buffer_len,
453                 const data_set_t *ds, const value_list_t *vl)
454 {
455         char *packet_ptr;
456         int packet_len;
457         int num_values;
458
459         part_header_t pkg_ph;
460         uint16_t      pkg_num_values;
461         uint8_t      *pkg_values_types;
462         value_t      *pkg_values;
463
464         int offset;
465         int i;
466
467         num_values = vl->values_len;
468         packet_len = sizeof (part_header_t) + sizeof (uint16_t)
469                 + (num_values * sizeof (uint8_t))
470                 + (num_values * sizeof (value_t));
471
472         if (*ret_buffer_len < packet_len)
473                 return (-1);
474
475         pkg_values_types = (uint8_t *) malloc (num_values * sizeof (uint8_t));
476         if (pkg_values_types == NULL)
477         {
478                 ERROR ("network plugin: write_part_values: malloc failed.");
479                 return (-1);
480         }
481
482         pkg_values = (value_t *) malloc (num_values * sizeof (value_t));
483         if (pkg_values == NULL)
484         {
485                 free (pkg_values_types);
486                 ERROR ("network plugin: write_part_values: malloc failed.");
487                 return (-1);
488         }
489
490         pkg_ph.type = htons (TYPE_VALUES);
491         pkg_ph.length = htons (packet_len);
492
493         pkg_num_values = htons ((uint16_t) vl->values_len);
494
495         for (i = 0; i < num_values; i++)
496         {
497                 pkg_values_types[i] = (uint8_t) ds->ds[i].type;
498                 switch (ds->ds[i].type)
499                 {
500                         case DS_TYPE_COUNTER:
501                                 pkg_values[i].counter = htonll (vl->values[i].counter);
502                                 break;
503
504                         case DS_TYPE_GAUGE:
505                                 pkg_values[i].gauge = htond (vl->values[i].gauge);
506                                 break;
507
508                         case DS_TYPE_DERIVE:
509                                 pkg_values[i].derive = htonll (vl->values[i].derive);
510                                 break;
511
512                         case DS_TYPE_ABSOLUTE:
513                                 pkg_values[i].absolute = htonll (vl->values[i].absolute);
514                                 break;
515
516                         default:
517                                 free (pkg_values_types);
518                                 free (pkg_values);
519                                 ERROR ("network plugin: write_part_values: "
520                                                 "Unknown data source type: %i",
521                                                 ds->ds[i].type);
522                                 return (-1);
523                 } /* switch (ds->ds[i].type) */
524         } /* for (num_values) */
525
526         /*
527          * Use `memcpy' to write everything to the buffer, because the pointer
528          * may be unaligned and some architectures, such as SPARC, can't handle
529          * that.
530          */
531         packet_ptr = *ret_buffer;
532         offset = 0;
533         memcpy (packet_ptr + offset, &pkg_ph, sizeof (pkg_ph));
534         offset += sizeof (pkg_ph);
535         memcpy (packet_ptr + offset, &pkg_num_values, sizeof (pkg_num_values));
536         offset += sizeof (pkg_num_values);
537         memcpy (packet_ptr + offset, pkg_values_types, num_values * sizeof (uint8_t));
538         offset += num_values * sizeof (uint8_t);
539         memcpy (packet_ptr + offset, pkg_values, num_values * sizeof (value_t));
540         offset += num_values * sizeof (value_t);
541
542         assert (offset == packet_len);
543
544         *ret_buffer = packet_ptr + packet_len;
545         *ret_buffer_len -= packet_len;
546
547         free (pkg_values_types);
548         free (pkg_values);
549
550         return (0);
551 } /* int write_part_values */
552
553 static int write_part_number (char **ret_buffer, int *ret_buffer_len,
554                 int type, uint64_t value)
555 {
556         char *packet_ptr;
557         int packet_len;
558
559         part_header_t pkg_head;
560         uint64_t pkg_value;
561         
562         int offset;
563
564         packet_len = sizeof (pkg_head) + sizeof (pkg_value);
565
566         if (*ret_buffer_len < packet_len)
567                 return (-1);
568
569         pkg_head.type = htons (type);
570         pkg_head.length = htons (packet_len);
571         pkg_value = htonll (value);
572
573         packet_ptr = *ret_buffer;
574         offset = 0;
575         memcpy (packet_ptr + offset, &pkg_head, sizeof (pkg_head));
576         offset += sizeof (pkg_head);
577         memcpy (packet_ptr + offset, &pkg_value, sizeof (pkg_value));
578         offset += sizeof (pkg_value);
579
580         assert (offset == packet_len);
581
582         *ret_buffer = packet_ptr + packet_len;
583         *ret_buffer_len -= packet_len;
584
585         return (0);
586 } /* int write_part_number */
587
588 static int write_part_string (char **ret_buffer, int *ret_buffer_len,
589                 int type, const char *str, int str_len)
590 {
591         char *buffer;
592         int buffer_len;
593
594         uint16_t pkg_type;
595         uint16_t pkg_length;
596
597         int offset;
598
599         buffer_len = 2 * sizeof (uint16_t) + str_len + 1;
600         if (*ret_buffer_len < buffer_len)
601                 return (-1);
602
603         pkg_type = htons (type);
604         pkg_length = htons (buffer_len);
605
606         buffer = *ret_buffer;
607         offset = 0;
608         memcpy (buffer + offset, (void *) &pkg_type, sizeof (pkg_type));
609         offset += sizeof (pkg_type);
610         memcpy (buffer + offset, (void *) &pkg_length, sizeof (pkg_length));
611         offset += sizeof (pkg_length);
612         memcpy (buffer + offset, str, str_len);
613         offset += str_len;
614         memset (buffer + offset, '\0', 1);
615         offset += 1;
616
617         assert (offset == buffer_len);
618
619         *ret_buffer = buffer + buffer_len;
620         *ret_buffer_len -= buffer_len;
621
622         return (0);
623 } /* int write_part_string */
624
625 static int parse_part_values (void **ret_buffer, size_t *ret_buffer_len,
626                 value_t **ret_values, int *ret_num_values)
627 {
628         char *buffer = *ret_buffer;
629         size_t buffer_len = *ret_buffer_len;
630
631         uint16_t tmp16;
632         size_t exp_size;
633         int   i;
634
635         uint16_t pkg_length;
636         uint16_t pkg_type;
637         uint16_t pkg_numval;
638
639         uint8_t *pkg_types;
640         value_t *pkg_values;
641
642         if (buffer_len < 15)
643         {
644                 NOTICE ("network plugin: packet is too short: "
645                                 "buffer_len = %zu", buffer_len);
646                 return (-1);
647         }
648
649         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
650         buffer += sizeof (tmp16);
651         pkg_type = ntohs (tmp16);
652
653         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
654         buffer += sizeof (tmp16);
655         pkg_length = ntohs (tmp16);
656
657         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
658         buffer += sizeof (tmp16);
659         pkg_numval = ntohs (tmp16);
660
661         assert (pkg_type == TYPE_VALUES);
662
663         exp_size = 3 * sizeof (uint16_t)
664                 + pkg_numval * (sizeof (uint8_t) + sizeof (value_t));
665         if ((buffer_len < 0) || (buffer_len < exp_size))
666         {
667                 WARNING ("network plugin: parse_part_values: "
668                                 "Packet too short: "
669                                 "Chunk of size %zu expected, "
670                                 "but buffer has only %zu bytes left.",
671                                 exp_size, buffer_len);
672                 return (-1);
673         }
674
675         if (pkg_length != exp_size)
676         {
677                 WARNING ("network plugin: parse_part_values: "
678                                 "Length and number of values "
679                                 "in the packet don't match.");
680                 return (-1);
681         }
682
683         pkg_types = (uint8_t *) malloc (pkg_numval * sizeof (uint8_t));
684         pkg_values = (value_t *) malloc (pkg_numval * sizeof (value_t));
685         if ((pkg_types == NULL) || (pkg_values == NULL))
686         {
687                 sfree (pkg_types);
688                 sfree (pkg_values);
689                 ERROR ("network plugin: parse_part_values: malloc failed.");
690                 return (-1);
691         }
692
693         memcpy ((void *) pkg_types, (void *) buffer, pkg_numval * sizeof (uint8_t));
694         buffer += pkg_numval * sizeof (uint8_t);
695         memcpy ((void *) pkg_values, (void *) buffer, pkg_numval * sizeof (value_t));
696         buffer += pkg_numval * sizeof (value_t);
697
698         for (i = 0; i < pkg_numval; i++)
699         {
700                 switch (pkg_types[i])
701                 {
702                   case DS_TYPE_COUNTER:
703                     pkg_values[i].counter = (counter_t) ntohll (pkg_values[i].counter);
704                     break;
705
706                   case DS_TYPE_GAUGE:
707                     pkg_values[i].gauge = (gauge_t) ntohd (pkg_values[i].gauge);
708                     break;
709
710                   case DS_TYPE_DERIVE:
711                     pkg_values[i].derive = (derive_t) ntohll (pkg_values[i].derive);
712                     break;
713
714                   case DS_TYPE_ABSOLUTE:
715                     pkg_values[i].absolute = (absolute_t) ntohll (pkg_values[i].absolute);
716                     break;
717
718                   default:
719                     sfree (pkg_types);
720                     sfree (pkg_values);
721                     NOTICE ("network plugin: parse_part_values: "
722                         "Don't know how to handle data source type %"PRIu8,
723                         pkg_types[i]);
724                     return (-1);
725                 } /* switch (pkg_types[i]) */
726         }
727
728         *ret_buffer     = buffer;
729         *ret_buffer_len = buffer_len - pkg_length;
730         *ret_num_values = pkg_numval;
731         *ret_values     = pkg_values;
732
733         sfree (pkg_types);
734
735         return (0);
736 } /* int parse_part_values */
737
738 static int parse_part_number (void **ret_buffer, size_t *ret_buffer_len,
739                 uint64_t *value)
740 {
741         char *buffer = *ret_buffer;
742         size_t buffer_len = *ret_buffer_len;
743
744         uint16_t tmp16;
745         uint64_t tmp64;
746         size_t exp_size = 2 * sizeof (uint16_t) + sizeof (uint64_t);
747
748         uint16_t pkg_length;
749         uint16_t pkg_type;
750
751         if ((buffer_len < 0) || ((size_t) buffer_len < exp_size))
752         {
753                 WARNING ("network plugin: parse_part_number: "
754                                 "Packet too short: "
755                                 "Chunk of size %zu expected, "
756                                 "but buffer has only %zu bytes left.",
757                                 exp_size, buffer_len);
758                 return (-1);
759         }
760
761         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
762         buffer += sizeof (tmp16);
763         pkg_type = ntohs (tmp16);
764
765         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
766         buffer += sizeof (tmp16);
767         pkg_length = ntohs (tmp16);
768
769         memcpy ((void *) &tmp64, buffer, sizeof (tmp64));
770         buffer += sizeof (tmp64);
771         *value = ntohll (tmp64);
772
773         *ret_buffer = buffer;
774         *ret_buffer_len = buffer_len - pkg_length;
775
776         return (0);
777 } /* int parse_part_number */
778
779 static int parse_part_string (void **ret_buffer, size_t *ret_buffer_len,
780                 char *output, int output_len)
781 {
782         char *buffer = *ret_buffer;
783         size_t buffer_len = *ret_buffer_len;
784
785         uint16_t tmp16;
786         size_t header_size = 2 * sizeof (uint16_t);
787
788         uint16_t pkg_length;
789         uint16_t pkg_type;
790
791         if ((buffer_len < 0) || (buffer_len < header_size))
792         {
793                 WARNING ("network plugin: parse_part_string: "
794                                 "Packet too short: "
795                                 "Chunk of at least size %zu expected, "
796                                 "but buffer has only %zu bytes left.",
797                                 header_size, buffer_len);
798                 return (-1);
799         }
800
801         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
802         buffer += sizeof (tmp16);
803         pkg_type = ntohs (tmp16);
804
805         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
806         buffer += sizeof (tmp16);
807         pkg_length = ntohs (tmp16);
808
809         /* Check that packet fits in the input buffer */
810         if (pkg_length > buffer_len)
811         {
812                 WARNING ("network plugin: parse_part_string: "
813                                 "Packet too big: "
814                                 "Chunk of size %"PRIu16" received, "
815                                 "but buffer has only %zu bytes left.",
816                                 pkg_length, buffer_len);
817                 return (-1);
818         }
819
820         /* Check that pkg_length is in the valid range */
821         if (pkg_length <= header_size)
822         {
823                 WARNING ("network plugin: parse_part_string: "
824                                 "Packet too short: "
825                                 "Header claims this packet is only %hu "
826                                 "bytes long.", pkg_length);
827                 return (-1);
828         }
829
830         /* Check that the package data fits into the output buffer.
831          * The previous if-statement ensures that:
832          * `pkg_length > header_size' */
833         if ((output_len < 0)
834                         || ((size_t) output_len < ((size_t) pkg_length - header_size)))
835         {
836                 WARNING ("network plugin: parse_part_string: "
837                                 "Output buffer too small.");
838                 return (-1);
839         }
840
841         /* All sanity checks successfull, let's copy the data over */
842         output_len = pkg_length - header_size;
843         memcpy ((void *) output, (void *) buffer, output_len);
844         buffer += output_len;
845
846         /* For some very weird reason '\0' doesn't do the trick on SPARC in
847          * this statement. */
848         if (output[output_len - 1] != 0)
849         {
850                 WARNING ("network plugin: parse_part_string: "
851                                 "Received string does not end "
852                                 "with a NULL-byte.");
853                 return (-1);
854         }
855
856         *ret_buffer = buffer;
857         *ret_buffer_len = buffer_len - pkg_length;
858
859         return (0);
860 } /* int parse_part_string */
861
862 /* Forward declaration: parse_part_sign_sha256 and parse_part_encr_aes256 call
863  * parse_packet and vice versa. */
864 #define PP_SIGNED    0x01
865 #define PP_ENCRYPTED 0x02
866 static int parse_packet (sockent_t *se,
867                 void *buffer, size_t buffer_size, int flags);
868
869 #define BUFFER_READ(p,s) do { \
870   memcpy ((p), buffer + buffer_offset, (s)); \
871   buffer_offset += (s); \
872 } while (0)
873
874 #if HAVE_LIBGCRYPT
875 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
876     void **ret_buffer, size_t *ret_buffer_len, int flags)
877 {
878   char *buffer;
879   size_t buffer_len;
880   size_t buffer_offset;
881
882   size_t username_len;
883   char *secret;
884
885   part_signature_sha256_t pss;
886   uint16_t pss_head_length;
887   char hash[sizeof (pss.hash)];
888
889   gcry_md_hd_t hd;
890   gcry_error_t err;
891   unsigned char *hash_ptr;
892
893   buffer = *ret_buffer;
894   buffer_len = *ret_buffer_len;
895   buffer_offset = 0;
896
897   if (se->data.server.userdb == NULL)
898   {
899     NOTICE ("network plugin: Received signed network packet but can't verify "
900         "it because no user DB has been configured. Will accept it.");
901     return (0);
902   }
903
904   /* Check if the buffer has enough data for this structure. */
905   if (buffer_len <= PART_SIGNATURE_SHA256_SIZE)
906     return (-ENOMEM);
907
908   /* Read type and length header */
909   BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
910   BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
911   pss_head_length = ntohs (pss.head.length);
912
913   /* Check if the `pss_head_length' is within bounds. */
914   if ((pss_head_length <= PART_SIGNATURE_SHA256_SIZE)
915       || (pss_head_length > buffer_len))
916   {
917     ERROR ("network plugin: HMAC-SHA-256 with invalid length received.");
918     return (-1);
919   }
920
921   /* Copy the hash. */
922   BUFFER_READ (pss.hash, sizeof (pss.hash));
923
924   /* Calculate username length (without null byte) and allocate memory */
925   username_len = pss_head_length - PART_SIGNATURE_SHA256_SIZE;
926   pss.username = malloc (username_len + 1);
927   if (pss.username == NULL)
928     return (-ENOMEM);
929
930   /* Read the username */
931   BUFFER_READ (pss.username, username_len);
932   pss.username[username_len] = 0;
933
934   assert (buffer_offset == pss_head_length);
935
936   /* Query the password */
937   secret = fbh_get (se->data.server.userdb, pss.username);
938   if (secret == NULL)
939   {
940     ERROR ("network plugin: Unknown user: %s", pss.username);
941     sfree (pss.username);
942     return (-ENOENT);
943   }
944
945   /* Create a hash device and check the HMAC */
946   hd = NULL;
947   err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
948   if (err != 0)
949   {
950     ERROR ("network plugin: Creating HMAC-SHA-256 object failed: %s",
951         gcry_strerror (err));
952     sfree (secret);
953     sfree (pss.username);
954     return (-1);
955   }
956
957   err = gcry_md_setkey (hd, secret, strlen (secret));
958   if (err != 0)
959   {
960     ERROR ("network plugin: gcry_md_setkey failed: %s", gcry_strerror (err));
961     gcry_md_close (hd);
962     return (-1);
963   }
964
965   gcry_md_write (hd,
966       buffer     + PART_SIGNATURE_SHA256_SIZE,
967       buffer_len - PART_SIGNATURE_SHA256_SIZE);
968   hash_ptr = gcry_md_read (hd, GCRY_MD_SHA256);
969   if (hash_ptr == NULL)
970   {
971     ERROR ("network plugin: gcry_md_read failed.");
972     gcry_md_close (hd);
973     sfree (secret);
974     sfree (pss.username);
975     return (-1);
976   }
977   memcpy (hash, hash_ptr, sizeof (hash));
978
979   /* Clean up */
980   gcry_md_close (hd);
981   hd = NULL;
982
983   sfree (secret);
984   sfree (pss.username);
985
986   if (memcmp (pss.hash, hash, sizeof (pss.hash)) != 0)
987   {
988     WARNING ("network plugin: Verifying HMAC-SHA-256 signature failed: "
989         "Hash mismatch.");
990   }
991   else
992   {
993     parse_packet (se, buffer + buffer_offset, buffer_len - buffer_offset,
994         flags | PP_SIGNED);
995   }
996
997   *ret_buffer = buffer + buffer_len;
998   *ret_buffer_len = 0;
999
1000   return (0);
1001 } /* }}} int parse_part_sign_sha256 */
1002 /* #endif HAVE_LIBGCRYPT */
1003
1004 #else /* if !HAVE_LIBGCRYPT */
1005 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
1006     void **ret_buffer, size_t *ret_buffer_size, int flags)
1007 {
1008   static int warning_has_been_printed = 0;
1009
1010   char *buffer;
1011   size_t buffer_size;
1012   size_t buffer_offset;
1013   uint16_t part_len;
1014
1015   part_signature_sha256_t pss;
1016
1017   buffer = *ret_buffer;
1018   buffer_size = *ret_buffer_size;
1019   buffer_offset = 0;
1020
1021   if (buffer_size <= PART_SIGNATURE_SHA256_SIZE)
1022     return (-ENOMEM);
1023
1024   BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1025   BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1026   part_len = ntohs (pss.head.length);
1027
1028   if ((part_len <= PART_SIGNATURE_SHA256_SIZE)
1029       || (part_len > buffer_size))
1030     return (-EINVAL);
1031
1032   if (warning_has_been_printed == 0)
1033   {
1034     WARNING ("network plugin: Received signed packet, but the network "
1035         "plugin was not linked with libgcrypt, so I cannot "
1036         "verify the signature. The packet will be accepted.");
1037     warning_has_been_printed = 1;
1038   }
1039
1040   parse_packet (se, buffer + part_len, buffer_size - part_len, flags);
1041
1042   *ret_buffer = buffer + buffer_size;
1043   *ret_buffer_size = 0;
1044
1045   return (0);
1046 } /* }}} int parse_part_sign_sha256 */
1047 #endif /* !HAVE_LIBGCRYPT */
1048
1049 #if HAVE_LIBGCRYPT
1050 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1051                 void **ret_buffer, size_t *ret_buffer_len,
1052                 int flags)
1053 {
1054   char  *buffer = *ret_buffer;
1055   size_t buffer_len = *ret_buffer_len;
1056   size_t payload_len;
1057   size_t part_size;
1058   size_t buffer_offset;
1059   uint16_t username_len;
1060   part_encryption_aes256_t pea;
1061   unsigned char hash[sizeof (pea.hash)];
1062
1063   gcry_cipher_hd_t cypher;
1064   gcry_error_t err;
1065
1066   /* Make sure at least the header if available. */
1067   if (buffer_len <= PART_ENCRYPTION_AES256_SIZE)
1068   {
1069     NOTICE ("network plugin: parse_part_encr_aes256: "
1070         "Discarding short packet.");
1071     return (-1);
1072   }
1073
1074   buffer_offset = 0;
1075
1076   /* Copy the unencrypted information into `pea'. */
1077   BUFFER_READ (&pea.head.type, sizeof (pea.head.type));
1078   BUFFER_READ (&pea.head.length, sizeof (pea.head.length));
1079
1080   /* Check the `part size'. */
1081   part_size = ntohs (pea.head.length);
1082   if ((part_size <= PART_ENCRYPTION_AES256_SIZE)
1083       || (part_size > buffer_len))
1084   {
1085     NOTICE ("network plugin: parse_part_encr_aes256: "
1086         "Discarding part with invalid size.");
1087     return (-1);
1088   }
1089
1090   /* Read the username */
1091   BUFFER_READ (&username_len, sizeof (username_len));
1092   username_len = ntohs (username_len);
1093
1094   if ((username_len <= 0)
1095       || (username_len > (part_size - (PART_ENCRYPTION_AES256_SIZE + 1))))
1096   {
1097     NOTICE ("network plugin: parse_part_encr_aes256: "
1098         "Discarding part with invalid username length.");
1099     return (-1);
1100   }
1101
1102   assert (username_len > 0);
1103   pea.username = malloc (username_len + 1);
1104   if (pea.username == NULL)
1105     return (-ENOMEM);
1106   BUFFER_READ (pea.username, username_len);
1107   pea.username[username_len] = 0;
1108
1109   /* Last but not least, the initialization vector */
1110   BUFFER_READ (pea.iv, sizeof (pea.iv));
1111
1112   /* Make sure we are at the right position */
1113   assert (buffer_offset == (username_len +
1114         PART_ENCRYPTION_AES256_SIZE - sizeof (pea.hash)));
1115
1116   cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
1117       pea.username);
1118   if (cypher == NULL)
1119     return (-1);
1120
1121   payload_len = part_size - (PART_ENCRYPTION_AES256_SIZE + username_len);
1122   assert (payload_len > 0);
1123
1124   /* Decrypt the packet in-place */
1125   err = gcry_cipher_decrypt (cypher,
1126       buffer    + buffer_offset,
1127       part_size - buffer_offset,
1128       /* in = */ NULL, /* in len = */ 0);
1129   if (err != 0)
1130   {
1131     ERROR ("network plugin: gcry_cipher_decrypt returned: %s",
1132         gcry_strerror (err));
1133     return (-1);
1134   }
1135
1136   /* Read the hash */
1137   BUFFER_READ (pea.hash, sizeof (pea.hash));
1138
1139   /* Make sure we're at the right position - again */
1140   assert (buffer_offset == (username_len + PART_ENCRYPTION_AES256_SIZE));
1141   assert (buffer_offset == (part_size - payload_len));
1142
1143   /* Check hash sum */
1144   memset (hash, 0, sizeof (hash));
1145   gcry_md_hash_buffer (GCRY_MD_SHA1, hash,
1146       buffer + buffer_offset, payload_len);
1147   if (memcmp (hash, pea.hash, sizeof (hash)) != 0)
1148   {
1149     ERROR ("network plugin: Decryption failed: Checksum mismatch.");
1150     return (-1);
1151   }
1152
1153   parse_packet (se, buffer + buffer_offset, payload_len,
1154       flags | PP_ENCRYPTED);
1155
1156   /* Update return values */
1157   *ret_buffer =     buffer     + part_size;
1158   *ret_buffer_len = buffer_len - part_size;
1159
1160   return (0);
1161 } /* }}} int parse_part_encr_aes256 */
1162 /* #endif HAVE_LIBGCRYPT */
1163
1164 #else /* if !HAVE_LIBGCRYPT */
1165 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1166     void **ret_buffer, size_t *ret_buffer_size, int flags)
1167 {
1168   static int warning_has_been_printed = 0;
1169
1170   char *buffer;
1171   size_t buffer_size;
1172   size_t buffer_offset;
1173
1174   part_header_t ph;
1175   size_t ph_length;
1176
1177   buffer = *ret_buffer;
1178   buffer_size = *ret_buffer_size;
1179   buffer_offset = 0;
1180
1181   /* parse_packet assures this minimum size. */
1182   assert (buffer_size >= (sizeof (ph.type) + sizeof (ph.length)));
1183
1184   BUFFER_READ (&ph.type, sizeof (ph.type));
1185   BUFFER_READ (&ph.length, sizeof (ph.length));
1186   ph_length = ntohs (ph.length);
1187
1188   if ((ph_length <= PART_ENCRYPTION_AES256_SIZE)
1189       || (ph_length > buffer_size))
1190   {
1191     ERROR ("network plugin: AES-256 encrypted part "
1192         "with invalid length received.");
1193     return (-1);
1194   }
1195
1196   if (warning_has_been_printed == 0)
1197   {
1198     WARNING ("network plugin: Received encrypted packet, but the network "
1199         "plugin was not linked with libgcrypt, so I cannot "
1200         "decrypt it. The part will be discarded.");
1201     warning_has_been_printed = 1;
1202   }
1203
1204   *ret_buffer += ph_length;
1205   *ret_buffer_size -= ph_length;
1206
1207   return (0);
1208 } /* }}} int parse_part_encr_aes256 */
1209 #endif /* !HAVE_LIBGCRYPT */
1210
1211 #undef BUFFER_READ
1212
1213 static int parse_packet (sockent_t *se, /* {{{ */
1214                 void *buffer, size_t buffer_size, int flags)
1215 {
1216         int status;
1217
1218         value_list_t vl = VALUE_LIST_INIT;
1219         notification_t n;
1220
1221 #if HAVE_LIBGCRYPT
1222         int packet_was_signed = (flags & PP_SIGNED);
1223         int packet_was_encrypted = (flags & PP_ENCRYPTED);
1224         int printed_ignore_warning = 0;
1225 #endif /* HAVE_LIBGCRYPT */
1226
1227
1228         memset (&vl, '\0', sizeof (vl));
1229         memset (&n, '\0', sizeof (n));
1230         status = 0;
1231
1232         while ((status == 0) && (0 < buffer_size)
1233                         && ((unsigned int) buffer_size > sizeof (part_header_t)))
1234         {
1235                 uint16_t pkg_length;
1236                 uint16_t pkg_type;
1237
1238                 memcpy ((void *) &pkg_type,
1239                                 (void *) buffer,
1240                                 sizeof (pkg_type));
1241                 memcpy ((void *) &pkg_length,
1242                                 (void *) (buffer + sizeof (pkg_type)),
1243                                 sizeof (pkg_length));
1244
1245                 pkg_length = ntohs (pkg_length);
1246                 pkg_type = ntohs (pkg_type);
1247
1248                 if (pkg_length > buffer_size)
1249                         break;
1250                 /* Ensure that this loop terminates eventually */
1251                 if (pkg_length < (2 * sizeof (uint16_t)))
1252                         break;
1253
1254                 if (pkg_type == TYPE_ENCR_AES256)
1255                 {
1256                         status = parse_part_encr_aes256 (se,
1257                                         &buffer, &buffer_size, flags);
1258                         if (status != 0)
1259                         {
1260                                 ERROR ("network plugin: Decrypting AES256 "
1261                                                 "part failed "
1262                                                 "with status %i.", status);
1263                                 break;
1264                         }
1265                 }
1266 #if HAVE_LIBGCRYPT
1267                 else if ((se->data.server.security_level == SECURITY_LEVEL_ENCRYPT)
1268                                 && (packet_was_encrypted == 0))
1269                 {
1270                         if (printed_ignore_warning == 0)
1271                         {
1272                                 INFO ("network plugin: Unencrypted packet or "
1273                                                 "part has been ignored.");
1274                                 printed_ignore_warning = 1;
1275                         }
1276                         buffer = ((char *) buffer) + pkg_length;
1277                         continue;
1278                 }
1279 #endif /* HAVE_LIBGCRYPT */
1280                 else if (pkg_type == TYPE_SIGN_SHA256)
1281                 {
1282                         status = parse_part_sign_sha256 (se,
1283                                         &buffer, &buffer_size, flags);
1284                         if (status != 0)
1285                         {
1286                                 ERROR ("network plugin: Verifying HMAC-SHA-256 "
1287                                                 "signature failed "
1288                                                 "with status %i.", status);
1289                                 break;
1290                         }
1291                 }
1292 #if HAVE_LIBGCRYPT
1293                 else if ((se->data.server.security_level == SECURITY_LEVEL_SIGN)
1294                                 && (packet_was_encrypted == 0)
1295                                 && (packet_was_signed == 0))
1296                 {
1297                         if (printed_ignore_warning == 0)
1298                         {
1299                                 INFO ("network plugin: Unsigned packet or "
1300                                                 "part has been ignored.");
1301                                 printed_ignore_warning = 1;
1302                         }
1303                         buffer = ((char *) buffer) + pkg_length;
1304                         continue;
1305                 }
1306 #endif /* HAVE_LIBGCRYPT */
1307                 else if (pkg_type == TYPE_VALUES)
1308                 {
1309                         status = parse_part_values (&buffer, &buffer_size,
1310                                         &vl.values, &vl.values_len);
1311                         if (status != 0)
1312                                 break;
1313
1314                         network_dispatch_values (&vl);
1315
1316                         sfree (vl.values);
1317                 }
1318                 else if (pkg_type == TYPE_TIME)
1319                 {
1320                         uint64_t tmp = 0;
1321                         status = parse_part_number (&buffer, &buffer_size,
1322                                         &tmp);
1323                         if (status == 0)
1324                         {
1325                                 vl.time = (time_t) tmp;
1326                                 n.time = (time_t) tmp;
1327                         }
1328                 }
1329                 else if (pkg_type == TYPE_INTERVAL)
1330                 {
1331                         uint64_t tmp = 0;
1332                         status = parse_part_number (&buffer, &buffer_size,
1333                                         &tmp);
1334                         if (status == 0)
1335                                 vl.interval = (int) tmp;
1336                 }
1337                 else if (pkg_type == TYPE_HOST)
1338                 {
1339                         status = parse_part_string (&buffer, &buffer_size,
1340                                         vl.host, sizeof (vl.host));
1341                         if (status == 0)
1342                                 sstrncpy (n.host, vl.host, sizeof (n.host));
1343                 }
1344                 else if (pkg_type == TYPE_PLUGIN)
1345                 {
1346                         status = parse_part_string (&buffer, &buffer_size,
1347                                         vl.plugin, sizeof (vl.plugin));
1348                         if (status == 0)
1349                                 sstrncpy (n.plugin, vl.plugin,
1350                                                 sizeof (n.plugin));
1351                 }
1352                 else if (pkg_type == TYPE_PLUGIN_INSTANCE)
1353                 {
1354                         status = parse_part_string (&buffer, &buffer_size,
1355                                         vl.plugin_instance,
1356                                         sizeof (vl.plugin_instance));
1357                         if (status == 0)
1358                                 sstrncpy (n.plugin_instance,
1359                                                 vl.plugin_instance,
1360                                                 sizeof (n.plugin_instance));
1361                 }
1362                 else if (pkg_type == TYPE_TYPE)
1363                 {
1364                         status = parse_part_string (&buffer, &buffer_size,
1365                                         vl.type, sizeof (vl.type));
1366                         if (status == 0)
1367                                 sstrncpy (n.type, vl.type, sizeof (n.type));
1368                 }
1369                 else if (pkg_type == TYPE_TYPE_INSTANCE)
1370                 {
1371                         status = parse_part_string (&buffer, &buffer_size,
1372                                         vl.type_instance,
1373                                         sizeof (vl.type_instance));
1374                         if (status == 0)
1375                                 sstrncpy (n.type_instance, vl.type_instance,
1376                                                 sizeof (n.type_instance));
1377                 }
1378                 else if (pkg_type == TYPE_MESSAGE)
1379                 {
1380                         status = parse_part_string (&buffer, &buffer_size,
1381                                         n.message, sizeof (n.message));
1382
1383                         if (status != 0)
1384                         {
1385                                 /* do nothing */
1386                         }
1387                         else if ((n.severity != NOTIF_FAILURE)
1388                                         && (n.severity != NOTIF_WARNING)
1389                                         && (n.severity != NOTIF_OKAY))
1390                         {
1391                                 INFO ("network plugin: "
1392                                                 "Ignoring notification with "
1393                                                 "unknown severity %i.",
1394                                                 n.severity);
1395                         }
1396                         else if (n.time <= 0)
1397                         {
1398                                 INFO ("network plugin: "
1399                                                 "Ignoring notification with "
1400                                                 "time == 0.");
1401                         }
1402                         else if (strlen (n.message) <= 0)
1403                         {
1404                                 INFO ("network plugin: "
1405                                                 "Ignoring notification with "
1406                                                 "an empty message.");
1407                         }
1408                         else
1409                         {
1410                                 plugin_dispatch_notification (&n);
1411                         }
1412                 }
1413                 else if (pkg_type == TYPE_SEVERITY)
1414                 {
1415                         uint64_t tmp = 0;
1416                         status = parse_part_number (&buffer, &buffer_size,
1417                                         &tmp);
1418                         if (status == 0)
1419                                 n.severity = (int) tmp;
1420                 }
1421                 else
1422                 {
1423                         DEBUG ("network plugin: parse_packet: Unknown part"
1424                                         " type: 0x%04hx", pkg_type);
1425                         buffer = ((char *) buffer) + pkg_length;
1426                 }
1427         } /* while (buffer_size > sizeof (part_header_t)) */
1428
1429         if (status == 0 && buffer_size > 0)
1430                 WARNING ("network plugin: parse_packet: Received truncated "
1431                                 "packet, try increasing `MaxPacketSize'");
1432
1433         return (status);
1434 } /* }}} int parse_packet */
1435
1436 static void free_sockent_client (struct sockent_client *sec) /* {{{ */
1437 {
1438   if (sec->fd >= 0)
1439   {
1440     close (sec->fd);
1441     sec->fd = -1;
1442   }
1443   sfree (sec->addr);
1444 #if HAVE_LIBGCRYPT
1445   sfree (sec->username);
1446   sfree (sec->password);
1447   if (sec->cypher != NULL)
1448     gcry_cipher_close (sec->cypher);
1449 #endif
1450 } /* }}} void free_sockent_client */
1451
1452 static void free_sockent_server (struct sockent_server *ses) /* {{{ */
1453 {
1454   size_t i;
1455
1456   for (i = 0; i < ses->fd_num; i++)
1457   {
1458     if (ses->fd[i] >= 0)
1459     {
1460       close (ses->fd[i]);
1461       ses->fd[i] = -1;
1462     }
1463   }
1464
1465   sfree (ses->fd);
1466 #if HAVE_LIBGCRYPT
1467   sfree (ses->auth_file);
1468   fbh_destroy (ses->userdb);
1469   if (ses->cypher != NULL)
1470     gcry_cipher_close (ses->cypher);
1471 #endif
1472 } /* }}} void free_sockent_server */
1473
1474 static void sockent_destroy (sockent_t *se) /* {{{ */
1475 {
1476   sockent_t *next;
1477
1478   DEBUG ("network plugin: sockent_destroy (se = %p);", (void *) se);
1479
1480   while (se != NULL)
1481   {
1482     next = se->next;
1483
1484     sfree (se->node);
1485     sfree (se->service);
1486
1487     if (se->type == SOCKENT_TYPE_CLIENT)
1488       free_sockent_client (&se->data.client);
1489     else
1490       free_sockent_server (&se->data.server);
1491
1492     sfree (se);
1493     se = next;
1494   }
1495 } /* }}} void sockent_destroy */
1496
1497 /*
1498  * int network_set_ttl
1499  *
1500  * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
1501  * `IPV6_UNICAST_HOPS', depending on which option is applicable.
1502  *
1503  * The `struct addrinfo' is used to destinguish between unicast and multicast
1504  * sockets.
1505  */
1506 static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
1507 {
1508         DEBUG ("network plugin: network_set_ttl: network_config_ttl = %i;",
1509                         network_config_ttl);
1510
1511         assert (se->type == SOCKENT_TYPE_CLIENT);
1512
1513         if ((network_config_ttl < 1) || (network_config_ttl > 255))
1514                 return (-1);
1515
1516         if (ai->ai_family == AF_INET)
1517         {
1518                 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1519                 int optname;
1520
1521                 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1522                         optname = IP_MULTICAST_TTL;
1523                 else
1524                         optname = IP_TTL;
1525
1526                 if (setsockopt (se->data.client.fd, IPPROTO_IP, optname,
1527                                         &network_config_ttl,
1528                                         sizeof (network_config_ttl)) == -1)
1529                 {
1530                         char errbuf[1024];
1531                         ERROR ("setsockopt: %s",
1532                                         sstrerror (errno, errbuf, sizeof (errbuf)));
1533                         return (-1);
1534                 }
1535         }
1536         else if (ai->ai_family == AF_INET6)
1537         {
1538                 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1539                 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1540                 int optname;
1541
1542                 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1543                         optname = IPV6_MULTICAST_HOPS;
1544                 else
1545                         optname = IPV6_UNICAST_HOPS;
1546
1547                 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, optname,
1548                                         &network_config_ttl,
1549                                         sizeof (network_config_ttl)) == -1)
1550                 {
1551                         char errbuf[1024];
1552                         ERROR ("setsockopt: %s",
1553                                         sstrerror (errno, errbuf,
1554                                                 sizeof (errbuf)));
1555                         return (-1);
1556                 }
1557         }
1558
1559         return (0);
1560 } /* int network_set_ttl */
1561
1562 static int network_bind_socket (int fd, const struct addrinfo *ai)
1563 {
1564         int loop = 0;
1565         int yes  = 1;
1566
1567         /* allow multiple sockets to use the same PORT number */
1568         if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
1569                                 &yes, sizeof(yes)) == -1) {
1570                 char errbuf[1024];
1571                 ERROR ("setsockopt: %s", 
1572                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1573                 return (-1);
1574         }
1575
1576         DEBUG ("fd = %i; calling `bind'", fd);
1577
1578         if (bind (fd, ai->ai_addr, ai->ai_addrlen) == -1)
1579         {
1580                 char errbuf[1024];
1581                 ERROR ("bind: %s",
1582                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1583                 return (-1);
1584         }
1585
1586         if (ai->ai_family == AF_INET)
1587         {
1588                 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1589                 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1590                 {
1591                         struct ip_mreq mreq;
1592
1593                         DEBUG ("fd = %i; IPv4 multicast address found", fd);
1594
1595                         mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1596                         mreq.imr_interface.s_addr = htonl (INADDR_ANY);
1597
1598                         if (setsockopt (fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1599                                                 &loop, sizeof (loop)) == -1)
1600                         {
1601                                 char errbuf[1024];
1602                                 ERROR ("setsockopt: %s",
1603                                                 sstrerror (errno, errbuf,
1604                                                         sizeof (errbuf)));
1605                                 return (-1);
1606                         }
1607
1608                         if (setsockopt (fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1609                                                 &mreq, sizeof (mreq)) == -1)
1610                         {
1611                                 char errbuf[1024];
1612                                 ERROR ("setsockopt: %s",
1613                                                 sstrerror (errno, errbuf,
1614                                                         sizeof (errbuf)));
1615                                 return (-1);
1616                         }
1617                 }
1618         }
1619         else if (ai->ai_family == AF_INET6)
1620         {
1621                 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1622                 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1623                 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1624                 {
1625                         struct ipv6_mreq mreq;
1626
1627                         DEBUG ("fd = %i; IPv6 multicast address found", fd);
1628
1629                         memcpy (&mreq.ipv6mr_multiaddr,
1630                                         &addr->sin6_addr,
1631                                         sizeof (addr->sin6_addr));
1632
1633                         /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
1634                          * ipv6mr_interface may be set to zeroes to
1635                          * choose the default multicast interface or to
1636                          * the index of a particular multicast-capable
1637                          * interface if the host is multihomed.
1638                          * Membership is associ-associated with a
1639                          * single interface; programs running on
1640                          * multihomed hosts may need to join the same
1641                          * group on more than one interface.*/
1642                         mreq.ipv6mr_interface = 0;
1643
1644                         if (setsockopt (fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1645                                                 &loop, sizeof (loop)) == -1)
1646                         {
1647                                 char errbuf[1024];
1648                                 ERROR ("setsockopt: %s",
1649                                                 sstrerror (errno, errbuf,
1650                                                         sizeof (errbuf)));
1651                                 return (-1);
1652                         }
1653
1654                         if (setsockopt (fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
1655                                                 &mreq, sizeof (mreq)) == -1)
1656                         {
1657                                 char errbuf[1024];
1658                                 ERROR ("setsockopt: %s",
1659                                                 sstrerror (errno, errbuf,
1660                                                         sizeof (errbuf)));
1661                                 return (-1);
1662                         }
1663                 }
1664         }
1665
1666         return (0);
1667 } /* int network_bind_socket */
1668
1669 /* Initialize a sockent structure. `type' must be either `SOCKENT_TYPE_CLIENT'
1670  * or `SOCKENT_TYPE_SERVER' */
1671 static int sockent_init (sockent_t *se, int type) /* {{{ */
1672 {
1673         if (se == NULL)
1674                 return (-1);
1675
1676         memset (se, 0, sizeof (*se));
1677
1678         se->type = SOCKENT_TYPE_CLIENT;
1679         se->node = NULL;
1680         se->service = NULL;
1681         se->next = NULL;
1682
1683         if (type == SOCKENT_TYPE_SERVER)
1684         {
1685                 se->type = SOCKENT_TYPE_SERVER;
1686                 se->data.server.fd = NULL;
1687 #if HAVE_LIBGCRYPT
1688                 se->data.server.security_level = SECURITY_LEVEL_NONE;
1689                 se->data.server.auth_file = NULL;
1690                 se->data.server.userdb = NULL;
1691                 se->data.server.cypher = NULL;
1692 #endif
1693         }
1694         else
1695         {
1696                 se->data.client.fd = -1;
1697                 se->data.client.addr = NULL;
1698 #if HAVE_LIBGCRYPT
1699                 se->data.client.security_level = SECURITY_LEVEL_NONE;
1700                 se->data.client.username = NULL;
1701                 se->data.client.password = NULL;
1702                 se->data.client.cypher = NULL;
1703 #endif
1704         }
1705
1706         return (0);
1707 } /* }}} int sockent_init */
1708
1709 /* Open the file descriptors for a initialized sockent structure. */
1710 static int sockent_open (sockent_t *se) /* {{{ */
1711 {
1712         struct addrinfo  ai_hints;
1713         struct addrinfo *ai_list, *ai_ptr;
1714         int              ai_return;
1715
1716         const char *node;
1717         const char *service;
1718
1719         if (se == NULL)
1720                 return (-1);
1721
1722         /* Set up the security structures. */
1723 #if HAVE_LIBGCRYPT /* {{{ */
1724         if (se->type == SOCKENT_TYPE_CLIENT)
1725         {
1726                 if (se->data.client.security_level > SECURITY_LEVEL_NONE)
1727                 {
1728                         if ((se->data.client.username == NULL)
1729                                         || (se->data.client.password == NULL))
1730                         {
1731                                 ERROR ("network plugin: Client socket with "
1732                                                 "security requested, but no "
1733                                                 "credentials are configured.");
1734                                 return (-1);
1735                         }
1736                         gcry_md_hash_buffer (GCRY_MD_SHA256,
1737                                         se->data.client.password_hash,
1738                                         se->data.client.password,
1739                                         strlen (se->data.client.password));
1740                 }
1741         }
1742         else /* (se->type == SOCKENT_TYPE_SERVER) */
1743         {
1744                 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
1745                 {
1746                         if (se->data.server.auth_file == NULL)
1747                         {
1748                                 ERROR ("network plugin: Server socket with "
1749                                                 "security requested, but no "
1750                                                 "password file is configured.");
1751                                 return (-1);
1752                         }
1753                 }
1754                 if (se->data.server.auth_file != NULL)
1755                 {
1756                         se->data.server.userdb = fbh_create (se->data.server.auth_file);
1757                         if (se->data.server.userdb == NULL)
1758                         {
1759                                 ERROR ("network plugin: Reading password file "
1760                                                 "`%s' failed.",
1761                                                 se->data.server.auth_file);
1762                                 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
1763                                         return (-1);
1764                         }
1765                 }
1766         }
1767 #endif /* }}} HAVE_LIBGCRYPT */
1768
1769         node = se->node;
1770         service = se->service;
1771
1772         if (service == NULL)
1773           service = NET_DEFAULT_PORT;
1774
1775         DEBUG ("network plugin: sockent_open: node = %s; service = %s;",
1776             node, service);
1777
1778         memset (&ai_hints, 0, sizeof (ai_hints));
1779         ai_hints.ai_flags  = 0;
1780 #ifdef AI_PASSIVE
1781         ai_hints.ai_flags |= AI_PASSIVE;
1782 #endif
1783 #ifdef AI_ADDRCONFIG
1784         ai_hints.ai_flags |= AI_ADDRCONFIG;
1785 #endif
1786         ai_hints.ai_family   = AF_UNSPEC;
1787         ai_hints.ai_socktype = SOCK_DGRAM;
1788         ai_hints.ai_protocol = IPPROTO_UDP;
1789
1790         ai_return = getaddrinfo (node, service, &ai_hints, &ai_list);
1791         if (ai_return != 0)
1792         {
1793                 ERROR ("network plugin: getaddrinfo (%s, %s) failed: %s",
1794                                 (se->node == NULL) ? "(null)" : se->node,
1795                                 (se->service == NULL) ? "(null)" : se->service,
1796                                 gai_strerror (ai_return));
1797                 return (-1);
1798         }
1799
1800         for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1801         {
1802                 int status;
1803
1804                 if (se->type == SOCKENT_TYPE_SERVER) /* {{{ */
1805                 {
1806                         int *tmp;
1807
1808                         tmp = realloc (se->data.server.fd,
1809                                         sizeof (*tmp) * (se->data.server.fd_num + 1));
1810                         if (tmp == NULL)
1811                         {
1812                                 ERROR ("network plugin: realloc failed.");
1813                                 continue;
1814                         }
1815                         se->data.server.fd = tmp;
1816                         tmp = se->data.server.fd + se->data.server.fd_num;
1817
1818                         *tmp = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
1819                                         ai_ptr->ai_protocol);
1820                         if (*tmp < 0)
1821                         {
1822                                 char errbuf[1024];
1823                                 ERROR ("network plugin: socket(2) failed: %s",
1824                                                 sstrerror (errno, errbuf,
1825                                                         sizeof (errbuf)));
1826                                 continue;
1827                         }
1828
1829                         status = network_bind_socket (*tmp, ai_ptr);
1830                         if (status != 0)
1831                         {
1832                                 close (*tmp);
1833                                 *tmp = -1;
1834                                 continue;
1835                         }
1836
1837                         se->data.server.fd_num++;
1838                         continue;
1839                 } /* }}} if (se->type == SOCKENT_TYPE_SERVER) */
1840                 else /* if (se->type == SOCKENT_TYPE_CLIENT) {{{ */
1841                 {
1842                         se->data.client.fd = socket (ai_ptr->ai_family,
1843                                         ai_ptr->ai_socktype,
1844                                         ai_ptr->ai_protocol);
1845                         if (se->data.client.fd < 0)
1846                         {
1847                                 char errbuf[1024];
1848                                 ERROR ("network plugin: socket(2) failed: %s",
1849                                                 sstrerror (errno, errbuf,
1850                                                         sizeof (errbuf)));
1851                                 continue;
1852                         }
1853
1854                         se->data.client.addr = malloc (sizeof (*se->data.client.addr));
1855                         if (se->data.client.addr == NULL)
1856                         {
1857                                 ERROR ("network plugin: malloc failed.");
1858                                 close (se->data.client.fd);
1859                                 se->data.client.fd = -1;
1860                                 continue;
1861                         }
1862
1863                         memset (se->data.client.addr, 0, sizeof (*se->data.client.addr));
1864                         assert (sizeof (*se->data.client.addr) >= ai_ptr->ai_addrlen);
1865                         memcpy (se->data.client.addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1866                         se->data.client.addrlen = ai_ptr->ai_addrlen;
1867
1868                         network_set_ttl (se, ai_ptr);
1869
1870                         /* We don't open more than one write-socket per
1871                          * node/service pair.. */
1872                         break;
1873                 } /* }}} if (se->type == SOCKENT_TYPE_CLIENT) */
1874         } /* for (ai_list) */
1875
1876         freeaddrinfo (ai_list);
1877
1878         /* Check if all went well. */
1879         if (se->type == SOCKENT_TYPE_SERVER)
1880         {
1881                 if (se->data.server.fd_num <= 0)
1882                         return (-1);
1883         }
1884         else /* if (se->type == SOCKENT_TYPE_CLIENT) */
1885         {
1886                 if (se->data.client.fd < 0)
1887                         return (-1);
1888         }
1889
1890         return (0);
1891 } /* }}} int sockent_open */
1892
1893 /* Add a sockent to the global list of sockets */
1894 static int sockent_add (sockent_t *se) /* {{{ */
1895 {
1896         sockent_t *last_ptr;
1897
1898         if (se == NULL)
1899                 return (-1);
1900
1901         if (se->type == SOCKENT_TYPE_SERVER)
1902         {
1903                 struct pollfd *tmp;
1904                 size_t i;
1905
1906                 tmp = realloc (listen_sockets_pollfd,
1907                                 sizeof (*tmp) * (listen_sockets_num
1908                                         + se->data.server.fd_num));
1909                 if (tmp == NULL)
1910                 {
1911                         ERROR ("network plugin: realloc failed.");
1912                         return (-1);
1913                 }
1914                 listen_sockets_pollfd = tmp;
1915                 tmp = listen_sockets_pollfd + listen_sockets_num;
1916
1917                 for (i = 0; i < se->data.server.fd_num; i++)
1918                 {
1919                         memset (tmp + i, 0, sizeof (*tmp));
1920                         tmp[i].fd = se->data.server.fd[i];
1921                         tmp[i].events = POLLIN | POLLPRI;
1922                         tmp[i].revents = 0;
1923                 }
1924
1925                 listen_sockets_num += se->data.server.fd_num;
1926
1927                 if (listen_sockets == NULL)
1928                 {
1929                         listen_sockets = se;
1930                         return (0);
1931                 }
1932                 last_ptr = listen_sockets;
1933         }
1934         else /* if (se->type == SOCKENT_TYPE_CLIENT) */
1935         {
1936                 if (sending_sockets == NULL)
1937                 {
1938                         sending_sockets = se;
1939                         return (0);
1940                 }
1941                 last_ptr = sending_sockets;
1942         }
1943
1944         while (last_ptr->next != NULL)
1945                 last_ptr = last_ptr->next;
1946         last_ptr->next = se;
1947
1948         return (0);
1949 } /* }}} int sockent_add */
1950
1951 static void *dispatch_thread (void __attribute__((unused)) *arg) /* {{{ */
1952 {
1953   while (42)
1954   {
1955     receive_list_entry_t *ent;
1956     sockent_t *se;
1957
1958     /* Lock and wait for more data to come in */
1959     pthread_mutex_lock (&receive_list_lock);
1960     while ((listen_loop == 0)
1961         && (receive_list_head == NULL))
1962       pthread_cond_wait (&receive_list_cond, &receive_list_lock);
1963
1964     /* Remove the head entry and unlock */
1965     ent = receive_list_head;
1966     if (ent != NULL)
1967       receive_list_head = ent->next;
1968     pthread_mutex_unlock (&receive_list_lock);
1969
1970     /* Check whether we are supposed to exit. We do NOT check `listen_loop'
1971      * because we dispatch all missing packets before shutting down. */
1972     if (ent == NULL)
1973       break;
1974
1975     /* Look for the correct `sockent_t' */
1976     se = listen_sockets;
1977     while (se != NULL)
1978     {
1979       size_t i;
1980
1981       for (i = 0; i < se->data.server.fd_num; i++)
1982         if (se->data.server.fd[i] == ent->fd)
1983           break;
1984
1985       if (i < se->data.server.fd_num)
1986         break;
1987
1988       se = se->next;
1989     }
1990
1991     if (se == NULL)
1992     {
1993             ERROR ("network plugin: Got packet from FD %i, but can't "
1994                             "find an appropriate socket entry.",
1995                             ent->fd);
1996             sfree (ent);
1997             continue;
1998     }
1999
2000     parse_packet (se, ent->data, ent->data_len, /* flags = */ 0);
2001     sfree (ent);
2002   } /* while (42) */
2003
2004   return (NULL);
2005 } /* }}} void *dispatch_thread */
2006
2007 static int network_receive (void) /* {{{ */
2008 {
2009         char buffer[network_config_packet_size];
2010         int  buffer_len;
2011
2012         int i;
2013         int status;
2014
2015         receive_list_entry_t *private_list_head;
2016         receive_list_entry_t *private_list_tail;
2017
2018         assert (listen_sockets_num > 0);
2019
2020         private_list_head = NULL;
2021         private_list_tail = NULL;
2022
2023         while (listen_loop == 0)
2024         {
2025                 status = poll (listen_sockets_pollfd, listen_sockets_num, -1);
2026
2027                 if (status <= 0)
2028                 {
2029                         char errbuf[1024];
2030                         if (errno == EINTR)
2031                                 continue;
2032                         ERROR ("poll failed: %s",
2033                                         sstrerror (errno, errbuf, sizeof (errbuf)));
2034                         return (-1);
2035                 }
2036
2037                 for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
2038                 {
2039                         receive_list_entry_t *ent;
2040
2041                         if ((listen_sockets_pollfd[i].revents
2042                                                 & (POLLIN | POLLPRI)) == 0)
2043                                 continue;
2044                         status--;
2045
2046                         buffer_len = recv (listen_sockets_pollfd[i].fd,
2047                                         buffer, sizeof (buffer),
2048                                         0 /* no flags */);
2049                         if (buffer_len < 0)
2050                         {
2051                                 char errbuf[1024];
2052                                 ERROR ("recv failed: %s",
2053                                                 sstrerror (errno, errbuf,
2054                                                         sizeof (errbuf)));
2055                                 return (-1);
2056                         }
2057
2058                         /* TODO: Possible performance enhancement: Do not free
2059                          * these entries in the dispatch thread but put them in
2060                          * another list, so we don't have to allocate more and
2061                          * more of these structures. */
2062                         ent = malloc (sizeof (receive_list_entry_t));
2063                         if (ent == NULL)
2064                         {
2065                                 ERROR ("network plugin: malloc failed.");
2066                                 return (-1);
2067                         }
2068                         memset (ent, 0, sizeof (receive_list_entry_t));
2069                         ent->data = malloc (network_config_packet_size);
2070                         if (ent->data == NULL)
2071                         {
2072                                 ERROR ("network plugin: malloc failed.");
2073                                 return (-1);
2074                         }
2075                         ent->fd = listen_sockets_pollfd[i].fd;
2076                         ent->next = NULL;
2077
2078                         /* Hopefully this be optimized out by the compiler. It
2079                          * might help prevent stupid bugs in the future though.
2080                          */
2081                         assert (sizeof (ent->data) == sizeof (buffer));
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, sizeof (send_buffer));
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                         sizeof (send_buffer) - (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                                 sizeof (send_buffer) - (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 ((sizeof (send_buffer) - 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         free (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         plugin_register_shutdown ("network", network_shutdown);
2941
2942         send_buffer = malloc (network_config_packet_size);
2943         if (send_buffer == NULL)
2944         {
2945                 ERROR ("network plugin: malloc failed.");
2946                 return (-1);
2947         }
2948         network_init_buffer ();
2949
2950         /* setup socket(s) and so on */
2951         if (sending_sockets != NULL)
2952         {
2953                 plugin_register_write ("network", network_write,
2954                                 /* user_data = */ NULL);
2955                 plugin_register_notification ("network", network_notification,
2956                                 /* user_data = */ NULL);
2957         }
2958
2959         /* If no threads need to be started, return here. */
2960         if ((listen_sockets_num == 0)
2961                         || ((dispatch_thread_running != 0)
2962                                 && (receive_thread_running != 0)))
2963                 return (0);
2964
2965         if (dispatch_thread_running == 0)
2966         {
2967                 int status;
2968                 status = pthread_create (&dispatch_thread_id,
2969                                 NULL /* no attributes */,
2970                                 dispatch_thread,
2971                                 NULL /* no argument */);
2972                 if (status != 0)
2973                 {
2974                         char errbuf[1024];
2975                         ERROR ("network: pthread_create failed: %s",
2976                                         sstrerror (errno, errbuf,
2977                                                 sizeof (errbuf)));
2978                 }
2979                 else
2980                 {
2981                         dispatch_thread_running = 1;
2982                 }
2983         }
2984
2985         if (receive_thread_running == 0)
2986         {
2987                 int status;
2988                 status = pthread_create (&receive_thread_id,
2989                                 NULL /* no attributes */,
2990                                 receive_thread,
2991                                 NULL /* no argument */);
2992                 if (status != 0)
2993                 {
2994                         char errbuf[1024];
2995                         ERROR ("network: pthread_create failed: %s",
2996                                         sstrerror (errno, errbuf,
2997                                                 sizeof (errbuf)));
2998                 }
2999                 else
3000                 {
3001                         receive_thread_running = 1;
3002                 }
3003         }
3004
3005         return (0);
3006 } /* int network_init */
3007
3008 /* 
3009  * The flush option of the network plugin cannot flush individual identifiers.
3010  * All the values are added to a buffer and sent when the buffer is full, the
3011  * requested value may or may not be in there, it's not worth finding out. We
3012  * just send the buffer if `flush'  is called - if the requested value was in
3013  * there, good. If not, well, then there is nothing to flush.. -octo
3014  */
3015 static int network_flush (int timeout,
3016                 const char __attribute__((unused)) *identifier,
3017                 user_data_t __attribute__((unused)) *user_data)
3018 {
3019         pthread_mutex_lock (&send_buffer_lock);
3020
3021         if (send_buffer_fill > 0)
3022           flush_buffer ();
3023
3024         pthread_mutex_unlock (&send_buffer_lock);
3025
3026         return (0);
3027 } /* int network_flush */
3028
3029 void module_register (void)
3030 {
3031         plugin_register_complex_config ("network", network_config);
3032         plugin_register_init   ("network", network_init);
3033         plugin_register_flush   ("network", network_flush,
3034                         /* user_data = */ NULL);
3035 } /* void module_register */
3036
3037 /* vim: set fdm=marker : */