network plugin: Remove a now invalid assertion.
[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                         memcpy (ent->data, buffer, buffer_len);
2079                         ent->data_len = buffer_len;
2080
2081                         if (private_list_head == NULL)
2082                                 private_list_head = ent;
2083                         else
2084                                 private_list_tail->next = ent;
2085                         private_list_tail = ent;
2086
2087                         /* Do not block here. Blocking here has led to
2088                          * insufficient performance in the past. */
2089                         if (pthread_mutex_trylock (&receive_list_lock) == 0)
2090                         {
2091                                 if (receive_list_head == NULL)
2092                                         receive_list_head = private_list_head;
2093                                 else
2094                                         receive_list_tail->next = private_list_head;
2095                                 receive_list_tail = private_list_tail;
2096
2097                                 private_list_head = NULL;
2098                                 private_list_tail = NULL;
2099
2100                                 pthread_cond_signal (&receive_list_cond);
2101                                 pthread_mutex_unlock (&receive_list_lock);
2102                         }
2103                 } /* for (listen_sockets_pollfd) */
2104         } /* while (listen_loop == 0) */
2105
2106         /* Make sure everything is dispatched before exiting. */
2107         if (private_list_head != NULL)
2108         {
2109                 pthread_mutex_lock (&receive_list_lock);
2110
2111                 if (receive_list_head == NULL)
2112                         receive_list_head = private_list_head;
2113                 else
2114                         receive_list_tail->next = private_list_head;
2115                 receive_list_tail = private_list_tail;
2116
2117                 private_list_head = NULL;
2118                 private_list_tail = NULL;
2119
2120                 pthread_cond_signal (&receive_list_cond);
2121                 pthread_mutex_unlock (&receive_list_lock);
2122         }
2123
2124         return (0);
2125 } /* }}} int network_receive */
2126
2127 static void *receive_thread (void __attribute__((unused)) *arg)
2128 {
2129         return (network_receive () ? (void *) 1 : (void *) 0);
2130 } /* void *receive_thread */
2131
2132 static void network_init_buffer (void)
2133 {
2134         memset (send_buffer, 0, sizeof (send_buffer));
2135         send_buffer_ptr = send_buffer;
2136         send_buffer_fill = 0;
2137
2138         memset (&send_buffer_vl, 0, sizeof (send_buffer_vl));
2139 } /* int network_init_buffer */
2140
2141 static void networt_send_buffer_plain (const sockent_t *se, /* {{{ */
2142                 const char *buffer, size_t buffer_size)
2143 {
2144         int status;
2145
2146         while (42)
2147         {
2148                 status = sendto (se->data.client.fd, buffer, buffer_size,
2149                     /* flags = */ 0,
2150                     (struct sockaddr *) se->data.client.addr,
2151                     se->data.client.addrlen);
2152                 if (status < 0)
2153                 {
2154                         char errbuf[1024];
2155                         if (errno == EINTR)
2156                                 continue;
2157                         ERROR ("network plugin: sendto failed: %s",
2158                                         sstrerror (errno, errbuf,
2159                                                 sizeof (errbuf)));
2160                         break;
2161                 }
2162
2163                 break;
2164         } /* while (42) */
2165 } /* }}} void networt_send_buffer_plain */
2166
2167 #if HAVE_LIBGCRYPT
2168 #define BUFFER_ADD(p,s) do { \
2169   memcpy (buffer + buffer_offset, (p), (s)); \
2170   buffer_offset += (s); \
2171 } while (0)
2172
2173 static void networt_send_buffer_signed (const sockent_t *se, /* {{{ */
2174                 const char *in_buffer, size_t in_buffer_size)
2175 {
2176   part_signature_sha256_t ps;
2177   char buffer[BUFF_SIG_SIZE + in_buffer_size];
2178   size_t buffer_offset;
2179   size_t username_len;
2180
2181   gcry_md_hd_t hd;
2182   gcry_error_t err;
2183   unsigned char *hash;
2184
2185   hd = NULL;
2186   err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
2187   if (err != 0)
2188   {
2189     ERROR ("network plugin: Creating HMAC object failed: %s",
2190         gcry_strerror (err));
2191     return;
2192   }
2193
2194   err = gcry_md_setkey (hd, se->data.client.password,
2195       strlen (se->data.client.password));
2196   if (err != 0)
2197   {
2198     ERROR ("network plugin: gcry_md_setkey failed: %s",
2199         gcry_strerror (err));
2200     gcry_md_close (hd);
2201     return;
2202   }
2203
2204   username_len = strlen (se->data.client.username);
2205   if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE))
2206   {
2207     ERROR ("network plugin: Username too long: %s",
2208         se->data.client.username);
2209     return;
2210   }
2211
2212   memcpy (buffer + PART_SIGNATURE_SHA256_SIZE,
2213       se->data.client.username, username_len);
2214   memcpy (buffer + PART_SIGNATURE_SHA256_SIZE + username_len,
2215       in_buffer, in_buffer_size);
2216
2217   /* Initialize the `ps' structure. */
2218   memset (&ps, 0, sizeof (ps));
2219   ps.head.type = htons (TYPE_SIGN_SHA256);
2220   ps.head.length = htons (PART_SIGNATURE_SHA256_SIZE + username_len);
2221
2222   /* Calculate the hash value. */
2223   gcry_md_write (hd, buffer + PART_SIGNATURE_SHA256_SIZE,
2224       username_len + in_buffer_size);
2225   hash = gcry_md_read (hd, GCRY_MD_SHA256);
2226   if (hash == NULL)
2227   {
2228     ERROR ("network plugin: gcry_md_read failed.");
2229     gcry_md_close (hd);
2230     return;
2231   }
2232   memcpy (ps.hash, hash, sizeof (ps.hash));
2233
2234   /* Add the header */
2235   buffer_offset = 0;
2236
2237   BUFFER_ADD (&ps.head.type, sizeof (ps.head.type));
2238   BUFFER_ADD (&ps.head.length, sizeof (ps.head.length));
2239   BUFFER_ADD (ps.hash, sizeof (ps.hash));
2240
2241   assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
2242
2243   gcry_md_close (hd);
2244   hd = NULL;
2245
2246   buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
2247   networt_send_buffer_plain (se, buffer, buffer_offset);
2248 } /* }}} void networt_send_buffer_signed */
2249
2250 static void networt_send_buffer_encrypted (sockent_t *se, /* {{{ */
2251                 const char *in_buffer, size_t in_buffer_size)
2252 {
2253   part_encryption_aes256_t pea;
2254   char buffer[BUFF_SIG_SIZE + in_buffer_size];
2255   size_t buffer_size;
2256   size_t buffer_offset;
2257   size_t header_size;
2258   size_t username_len;
2259   gcry_error_t err;
2260   gcry_cipher_hd_t cypher;
2261
2262   /* Initialize the header fields */
2263   memset (&pea, 0, sizeof (pea));
2264   pea.head.type = htons (TYPE_ENCR_AES256);
2265
2266   pea.username = se->data.client.username;
2267
2268   username_len = strlen (pea.username);
2269   if ((PART_ENCRYPTION_AES256_SIZE + username_len) > BUFF_SIG_SIZE)
2270   {
2271     ERROR ("network plugin: Username too long: %s", pea.username);
2272     return;
2273   }
2274
2275   buffer_size = PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size;
2276   header_size = PART_ENCRYPTION_AES256_SIZE + username_len
2277     - sizeof (pea.hash);
2278
2279   assert (buffer_size <= sizeof (buffer));
2280   DEBUG ("network plugin: networt_send_buffer_encrypted: "
2281       "buffer_size = %zu;", buffer_size);
2282
2283   pea.head.length = htons ((uint16_t) (PART_ENCRYPTION_AES256_SIZE
2284         + username_len + in_buffer_size));
2285   pea.username_length = htons ((uint16_t) username_len);
2286
2287   /* Chose a random initialization vector. */
2288   gcry_randomize ((void *) &pea.iv, sizeof (pea.iv), GCRY_STRONG_RANDOM);
2289
2290   /* Create hash of the payload */
2291   gcry_md_hash_buffer (GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
2292
2293   /* Initialize the buffer */
2294   buffer_offset = 0;
2295   memset (buffer, 0, sizeof (buffer));
2296
2297
2298   BUFFER_ADD (&pea.head.type, sizeof (pea.head.type));
2299   BUFFER_ADD (&pea.head.length, sizeof (pea.head.length));
2300   BUFFER_ADD (&pea.username_length, sizeof (pea.username_length));
2301   BUFFER_ADD (pea.username, username_len);
2302   BUFFER_ADD (pea.iv, sizeof (pea.iv));
2303   assert (buffer_offset == header_size);
2304   BUFFER_ADD (pea.hash, sizeof (pea.hash));
2305   BUFFER_ADD (in_buffer, in_buffer_size);
2306
2307   assert (buffer_offset == buffer_size);
2308
2309   cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
2310       se->data.client.password);
2311   if (cypher == NULL)
2312     return;
2313
2314   /* Encrypt the buffer in-place */
2315   err = gcry_cipher_encrypt (cypher,
2316       buffer      + header_size,
2317       buffer_size - header_size,
2318       /* in = */ NULL, /* in len = */ 0);
2319   if (err != 0)
2320   {
2321     ERROR ("network plugin: gcry_cipher_encrypt returned: %s",
2322         gcry_strerror (err));
2323     return;
2324   }
2325
2326   /* Send it out without further modifications */
2327   networt_send_buffer_plain (se, buffer, buffer_size);
2328 } /* }}} void networt_send_buffer_encrypted */
2329 #undef BUFFER_ADD
2330 #endif /* HAVE_LIBGCRYPT */
2331
2332 static void network_send_buffer (char *buffer, size_t buffer_len) /* {{{ */
2333 {
2334   sockent_t *se;
2335
2336   DEBUG ("network plugin: network_send_buffer: buffer_len = %zu", buffer_len);
2337
2338   for (se = sending_sockets; se != NULL; se = se->next)
2339   {
2340 #if HAVE_LIBGCRYPT
2341     if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
2342       networt_send_buffer_encrypted (se, buffer, buffer_len);
2343     else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
2344       networt_send_buffer_signed (se, buffer, buffer_len);
2345     else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
2346 #endif /* HAVE_LIBGCRYPT */
2347       networt_send_buffer_plain (se, buffer, buffer_len);
2348   } /* for (sending_sockets) */
2349 } /* }}} void network_send_buffer */
2350
2351 static int add_to_buffer (char *buffer, int buffer_size, /* {{{ */
2352                 value_list_t *vl_def,
2353                 const data_set_t *ds, const value_list_t *vl)
2354 {
2355         char *buffer_orig = buffer;
2356
2357         if (strcmp (vl_def->host, vl->host) != 0)
2358         {
2359                 if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
2360                                         vl->host, strlen (vl->host)) != 0)
2361                         return (-1);
2362                 sstrncpy (vl_def->host, vl->host, sizeof (vl_def->host));
2363         }
2364
2365         if (vl_def->time != vl->time)
2366         {
2367                 if (write_part_number (&buffer, &buffer_size, TYPE_TIME,
2368                                         (uint64_t) vl->time))
2369                         return (-1);
2370                 vl_def->time = vl->time;
2371         }
2372
2373         if (vl_def->interval != vl->interval)
2374         {
2375                 if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL,
2376                                         (uint64_t) vl->interval))
2377                         return (-1);
2378                 vl_def->interval = vl->interval;
2379         }
2380
2381         if (strcmp (vl_def->plugin, vl->plugin) != 0)
2382         {
2383                 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
2384                                         vl->plugin, strlen (vl->plugin)) != 0)
2385                         return (-1);
2386                 sstrncpy (vl_def->plugin, vl->plugin, sizeof (vl_def->plugin));
2387         }
2388
2389         if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
2390         {
2391                 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
2392                                         vl->plugin_instance,
2393                                         strlen (vl->plugin_instance)) != 0)
2394                         return (-1);
2395                 sstrncpy (vl_def->plugin_instance, vl->plugin_instance, sizeof (vl_def->plugin_instance));
2396         }
2397
2398         if (strcmp (vl_def->type, vl->type) != 0)
2399         {
2400                 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
2401                                         vl->type, strlen (vl->type)) != 0)
2402                         return (-1);
2403                 sstrncpy (vl_def->type, ds->type, sizeof (vl_def->type));
2404         }
2405
2406         if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
2407         {
2408                 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
2409                                         vl->type_instance,
2410                                         strlen (vl->type_instance)) != 0)
2411                         return (-1);
2412                 sstrncpy (vl_def->type_instance, vl->type_instance, sizeof (vl_def->type_instance));
2413         }
2414         
2415         if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
2416                 return (-1);
2417
2418         return (buffer - buffer_orig);
2419 } /* }}} int add_to_buffer */
2420
2421 static void flush_buffer (void)
2422 {
2423         DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
2424                         send_buffer_fill);
2425
2426         network_send_buffer (send_buffer, (size_t) send_buffer_fill);
2427         network_init_buffer ();
2428 }
2429
2430 static int network_write (const data_set_t *ds, const value_list_t *vl,
2431                 user_data_t __attribute__((unused)) *user_data)
2432 {
2433         int status;
2434
2435         if (!check_send_okay (vl))
2436         {
2437 #if COLLECT_DEBUG
2438           char name[6*DATA_MAX_NAME_LEN];
2439           FORMAT_VL (name, sizeof (name), vl);
2440           name[sizeof (name) - 1] = 0;
2441           DEBUG ("network plugin: network_write: "
2442               "NOT sending %s.", name);
2443 #endif
2444           return (0);
2445         }
2446
2447         uc_meta_data_add_unsigned_int (vl,
2448             "network:time_sent", (uint64_t) vl->time);
2449
2450         pthread_mutex_lock (&send_buffer_lock);
2451
2452         status = add_to_buffer (send_buffer_ptr,
2453                         sizeof (send_buffer) - (send_buffer_fill + BUFF_SIG_SIZE),
2454                         &send_buffer_vl,
2455                         ds, vl);
2456         if (status >= 0)
2457         {
2458                 /* status == bytes added to the buffer */
2459                 send_buffer_fill += status;
2460                 send_buffer_ptr  += status;
2461         }
2462         else
2463         {
2464                 flush_buffer ();
2465
2466                 status = add_to_buffer (send_buffer_ptr,
2467                                 sizeof (send_buffer) - (send_buffer_fill + BUFF_SIG_SIZE),
2468                                 &send_buffer_vl,
2469                                 ds, vl);
2470
2471                 if (status >= 0)
2472                 {
2473                         send_buffer_fill += status;
2474                         send_buffer_ptr  += status;
2475                 }
2476         }
2477
2478         if (status < 0)
2479         {
2480                 ERROR ("network plugin: Unable to append to the "
2481                                 "buffer for some weird reason");
2482         }
2483         else if ((sizeof (send_buffer) - send_buffer_fill) < 15)
2484         {
2485                 flush_buffer ();
2486         }
2487
2488         pthread_mutex_unlock (&send_buffer_lock);
2489
2490         return ((status < 0) ? -1 : 0);
2491 } /* int network_write */
2492
2493 static int network_config_set_boolean (const oconfig_item_t *ci, /* {{{ */
2494     int *retval)
2495 {
2496   if ((ci->values_num != 1)
2497       || ((ci->values[0].type != OCONFIG_TYPE_BOOLEAN)
2498         && (ci->values[0].type != OCONFIG_TYPE_STRING)))
2499   {
2500     ERROR ("network plugin: The `%s' config option needs "
2501         "exactly one boolean argument.", ci->key);
2502     return (-1);
2503   }
2504
2505   if (ci->values[0].type == OCONFIG_TYPE_BOOLEAN)
2506   {
2507     if (ci->values[0].value.boolean)
2508       *retval = 1;
2509     else
2510       *retval = 0;
2511   }
2512   else
2513   {
2514     char *str = ci->values[0].value.string;
2515
2516     if ((strcasecmp ("true", str) == 0)
2517         || (strcasecmp ("yes", str) == 0)
2518         || (strcasecmp ("on", str) == 0))
2519       *retval = 1;
2520     else if ((strcasecmp ("false", str) == 0)
2521         || (strcasecmp ("no", str) == 0)
2522         || (strcasecmp ("off", str) == 0))
2523       *retval = 0;
2524     else
2525     {
2526       ERROR ("network plugin: Cannot parse string value `%s' of the `%s' "
2527           "option as boolean value.",
2528           str, ci->key);
2529       return (-1);
2530     }
2531   }
2532
2533   return (0);
2534 } /* }}} int network_config_set_boolean */
2535
2536 static int network_config_set_ttl (const oconfig_item_t *ci) /* {{{ */
2537 {
2538   int tmp;
2539   if ((ci->values_num != 1)
2540       || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2541   {
2542     WARNING ("network plugin: The `TimeToLive' config option needs exactly "
2543         "one numeric argument.");
2544     return (-1);
2545   }
2546
2547   tmp = (int) ci->values[0].value.number;
2548   if ((tmp > 0) && (tmp <= 255))
2549     network_config_ttl = tmp;
2550
2551   return (0);
2552 } /* }}} int network_config_set_ttl */
2553
2554 static int network_config_set_buffer_size (const oconfig_item_t *ci) /* {{{ */
2555 {
2556   int tmp;
2557   if ((ci->values_num != 1)
2558       || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2559   {
2560     WARNING ("network plugin: The `MaxPacketSize' config option needs exactly "
2561         "one numeric argument.");
2562     return (-1);
2563   }
2564
2565   tmp = (int) ci->values[0].value.number;
2566   if ((tmp >= 1024) && (tmp <= 65535))
2567     network_config_packet_size = tmp;
2568
2569   return (0);
2570 } /* }}} int network_config_set_buffer_size */
2571
2572 #if HAVE_LIBGCRYPT
2573 static int network_config_set_string (const oconfig_item_t *ci, /* {{{ */
2574     char **ret_string)
2575 {
2576   char *tmp;
2577   if ((ci->values_num != 1)
2578       || (ci->values[0].type != OCONFIG_TYPE_STRING))
2579   {
2580     WARNING ("network plugin: The `%s' config option needs exactly "
2581         "one string argument.", ci->key);
2582     return (-1);
2583   }
2584
2585   tmp = strdup (ci->values[0].value.string);
2586   if (tmp == NULL)
2587     return (-1);
2588
2589   sfree (*ret_string);
2590   *ret_string = tmp;
2591
2592   return (0);
2593 } /* }}} int network_config_set_string */
2594 #endif /* HAVE_LIBGCRYPT */
2595
2596 #if HAVE_LIBGCRYPT
2597 static int network_config_set_security_level (oconfig_item_t *ci, /* {{{ */
2598     int *retval)
2599 {
2600   char *str;
2601   if ((ci->values_num != 1)
2602       || (ci->values[0].type != OCONFIG_TYPE_STRING))
2603   {
2604     WARNING ("network plugin: The `SecurityLevel' config option needs exactly "
2605         "one string argument.");
2606     return (-1);
2607   }
2608
2609   str = ci->values[0].value.string;
2610   if (strcasecmp ("Encrypt", str) == 0)
2611     *retval = SECURITY_LEVEL_ENCRYPT;
2612   else if (strcasecmp ("Sign", str) == 0)
2613     *retval = SECURITY_LEVEL_SIGN;
2614   else if (strcasecmp ("None", str) == 0)
2615     *retval = SECURITY_LEVEL_NONE;
2616   else
2617   {
2618     WARNING ("network plugin: Unknown security level: %s.", str);
2619     return (-1);
2620   }
2621
2622   return (0);
2623 } /* }}} int network_config_set_security_level */
2624 #endif /* HAVE_LIBGCRYPT */
2625
2626 static int network_config_add_listen (const oconfig_item_t *ci) /* {{{ */
2627 {
2628   sockent_t *se;
2629   int status;
2630   int i;
2631
2632   if ((ci->values_num < 1) || (ci->values_num > 2)
2633       || (ci->values[0].type != OCONFIG_TYPE_STRING)
2634       || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
2635   {
2636     ERROR ("network plugin: The `%s' config option needs "
2637         "one or two string arguments.", ci->key);
2638     return (-1);
2639   }
2640
2641   se = malloc (sizeof (*se));
2642   if (se == NULL)
2643   {
2644     ERROR ("network plugin: malloc failed.");
2645     return (-1);
2646   }
2647   sockent_init (se, SOCKENT_TYPE_SERVER);
2648
2649   se->node = strdup (ci->values[0].value.string);
2650   if (ci->values_num >= 2)
2651     se->service = strdup (ci->values[1].value.string);
2652
2653   for (i = 0; i < ci->children_num; i++)
2654   {
2655     oconfig_item_t *child = ci->children + i;
2656
2657 #if HAVE_LIBGCRYPT
2658     if (strcasecmp ("AuthFile", child->key) == 0)
2659       network_config_set_string (child, &se->data.server.auth_file);
2660     else if (strcasecmp ("SecurityLevel", child->key) == 0)
2661       network_config_set_security_level (child,
2662           &se->data.server.security_level);
2663     else
2664 #endif /* HAVE_LIBGCRYPT */
2665     {
2666       WARNING ("network plugin: Option `%s' is not allowed here.",
2667           child->key);
2668     }
2669   }
2670
2671 #if HAVE_LIBGCRYPT
2672   if ((se->data.server.security_level > SECURITY_LEVEL_NONE)
2673       && (se->data.server.auth_file == NULL))
2674   {
2675     ERROR ("network plugin: A security level higher than `none' was "
2676         "requested, but no AuthFile option was given. Cowardly refusing to "
2677         "open this socket!");
2678     sockent_destroy (se);
2679     return (-1);
2680   }
2681 #endif /* HAVE_LIBGCRYPT */
2682
2683   status = sockent_open (se);
2684   if (status != 0)
2685   {
2686     ERROR ("network plugin: network_config_add_listen: sockent_open failed.");
2687     sockent_destroy (se);
2688     return (-1);
2689   }
2690
2691   status = sockent_add (se);
2692   if (status != 0)
2693   {
2694     ERROR ("network plugin: network_config_add_listen: sockent_add failed.");
2695     sockent_destroy (se);
2696     return (-1);
2697   }
2698
2699   return (0);
2700 } /* }}} int network_config_add_listen */
2701
2702 static int network_config_add_server (const oconfig_item_t *ci) /* {{{ */
2703 {
2704   sockent_t *se;
2705   int status;
2706   int i;
2707
2708   if ((ci->values_num < 1) || (ci->values_num > 2)
2709       || (ci->values[0].type != OCONFIG_TYPE_STRING)
2710       || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
2711   {
2712     ERROR ("network plugin: The `%s' config option needs "
2713         "one or two string arguments.", ci->key);
2714     return (-1);
2715   }
2716
2717   se = malloc (sizeof (*se));
2718   if (se == NULL)
2719   {
2720     ERROR ("network plugin: malloc failed.");
2721     return (-1);
2722   }
2723   sockent_init (se, SOCKENT_TYPE_CLIENT);
2724
2725   se->node = strdup (ci->values[0].value.string);
2726   if (ci->values_num >= 2)
2727     se->service = strdup (ci->values[1].value.string);
2728
2729   for (i = 0; i < ci->children_num; i++)
2730   {
2731     oconfig_item_t *child = ci->children + i;
2732
2733 #if HAVE_LIBGCRYPT
2734     if (strcasecmp ("Username", child->key) == 0)
2735       network_config_set_string (child, &se->data.client.username);
2736     else if (strcasecmp ("Password", child->key) == 0)
2737       network_config_set_string (child, &se->data.client.password);
2738     else if (strcasecmp ("SecurityLevel", child->key) == 0)
2739       network_config_set_security_level (child,
2740           &se->data.client.security_level);
2741     else
2742 #endif /* HAVE_LIBGCRYPT */
2743     {
2744       WARNING ("network plugin: Option `%s' is not allowed here.",
2745           child->key);
2746     }
2747   }
2748
2749 #if HAVE_LIBGCRYPT
2750   if ((se->data.client.security_level > SECURITY_LEVEL_NONE)
2751       && ((se->data.client.username == NULL)
2752         || (se->data.client.password == NULL)))
2753   {
2754     ERROR ("network plugin: A security level higher than `none' was "
2755         "requested, but no Username or Password option was given. "
2756         "Cowardly refusing to open this socket!");
2757     sockent_destroy (se);
2758     return (-1);
2759   }
2760 #endif /* HAVE_LIBGCRYPT */
2761
2762   status = sockent_open (se);
2763   if (status != 0)
2764   {
2765     ERROR ("network plugin: network_config_add_server: sockent_open failed.");
2766     sockent_destroy (se);
2767     return (-1);
2768   }
2769
2770   status = sockent_add (se);
2771   if (status != 0)
2772   {
2773     ERROR ("network plugin: network_config_add_server: sockent_add failed.");
2774     sockent_destroy (se);
2775     return (-1);
2776   }
2777
2778   return (0);
2779 } /* }}} int network_config_add_server */
2780
2781 static int network_config (oconfig_item_t *ci) /* {{{ */
2782 {
2783   int i;
2784
2785   for (i = 0; i < ci->children_num; i++)
2786   {
2787     oconfig_item_t *child = ci->children + i;
2788
2789     if (strcasecmp ("Listen", child->key) == 0)
2790       network_config_add_listen (child);
2791     else if (strcasecmp ("Server", child->key) == 0)
2792       network_config_add_server (child);
2793     else if (strcasecmp ("TimeToLive", child->key) == 0)
2794       network_config_set_ttl (child);
2795     else if (strcasecmp ("MaxPacketSize", child->key) == 0)
2796       network_config_set_buffer_size (child);
2797     else if (strcasecmp ("Forward", child->key) == 0)
2798       network_config_set_boolean (child, &network_config_forward);
2799     else if (strcasecmp ("CacheFlush", child->key) == 0)
2800       /* no op for backwards compatibility only */;
2801     else
2802     {
2803       WARNING ("network plugin: Option `%s' is not allowed here.",
2804           child->key);
2805     }
2806   }
2807
2808   return (0);
2809 } /* }}} int network_config */
2810
2811 static int network_notification (const notification_t *n,
2812                 user_data_t __attribute__((unused)) *user_data)
2813 {
2814   char  buffer[network_config_packet_size];
2815   char *buffer_ptr = buffer;
2816   int   buffer_free = sizeof (buffer);
2817   int   status;
2818
2819   memset (buffer, '\0', sizeof (buffer));
2820
2821
2822   status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME,
2823       (uint64_t) n->time);
2824   if (status != 0)
2825     return (-1);
2826
2827   status = write_part_number (&buffer_ptr, &buffer_free, TYPE_SEVERITY,
2828       (uint64_t) n->severity);
2829   if (status != 0)
2830     return (-1);
2831
2832   if (strlen (n->host) > 0)
2833   {
2834     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_HOST,
2835         n->host, strlen (n->host));
2836     if (status != 0)
2837       return (-1);
2838   }
2839
2840   if (strlen (n->plugin) > 0)
2841   {
2842     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_PLUGIN,
2843         n->plugin, strlen (n->plugin));
2844     if (status != 0)
2845       return (-1);
2846   }
2847
2848   if (strlen (n->plugin_instance) > 0)
2849   {
2850     status = write_part_string (&buffer_ptr, &buffer_free,
2851         TYPE_PLUGIN_INSTANCE,
2852         n->plugin_instance, strlen (n->plugin_instance));
2853     if (status != 0)
2854       return (-1);
2855   }
2856
2857   if (strlen (n->type) > 0)
2858   {
2859     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE,
2860         n->type, strlen (n->type));
2861     if (status != 0)
2862       return (-1);
2863   }
2864
2865   if (strlen (n->type_instance) > 0)
2866   {
2867     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
2868         n->type_instance, strlen (n->type_instance));
2869     if (status != 0)
2870       return (-1);
2871   }
2872
2873   status = write_part_string (&buffer_ptr, &buffer_free, TYPE_MESSAGE,
2874       n->message, strlen (n->message));
2875   if (status != 0)
2876     return (-1);
2877
2878   network_send_buffer (buffer, sizeof (buffer) - buffer_free);
2879
2880   return (0);
2881 } /* int network_notification */
2882
2883 static int network_shutdown (void)
2884 {
2885         listen_loop++;
2886
2887         /* Kill the listening thread */
2888         if (receive_thread_running != 0)
2889         {
2890                 INFO ("network plugin: Stopping receive thread.");
2891                 pthread_kill (receive_thread_id, SIGTERM);
2892                 pthread_join (receive_thread_id, NULL /* no return value */);
2893                 memset (&receive_thread_id, 0, sizeof (receive_thread_id));
2894                 receive_thread_running = 0;
2895         }
2896
2897         /* Shutdown the dispatching thread */
2898         if (dispatch_thread_running != 0)
2899         {
2900                 INFO ("network plugin: Stopping dispatch thread.");
2901                 pthread_mutex_lock (&receive_list_lock);
2902                 pthread_cond_broadcast (&receive_list_cond);
2903                 pthread_mutex_unlock (&receive_list_lock);
2904                 pthread_join (dispatch_thread_id, /* ret = */ NULL);
2905                 dispatch_thread_running = 0;
2906         }
2907
2908         sockent_destroy (listen_sockets);
2909
2910         if (send_buffer_fill > 0)
2911                 flush_buffer ();
2912
2913         free (send_buffer);
2914
2915         /* TODO: Close `sending_sockets' */
2916
2917         plugin_unregister_config ("network");
2918         plugin_unregister_init ("network");
2919         plugin_unregister_write ("network");
2920         plugin_unregister_shutdown ("network");
2921
2922         return (0);
2923 } /* int network_shutdown */
2924
2925 static int network_init (void)
2926 {
2927         static _Bool have_init = false;
2928
2929         /* Check if we were already initialized. If so, just return - there's
2930          * nothing more to do (for now, that is). */
2931         if (have_init)
2932                 return (0);
2933         have_init = true;
2934
2935         plugin_register_shutdown ("network", network_shutdown);
2936
2937         send_buffer = malloc (network_config_packet_size);
2938         if (send_buffer == NULL)
2939         {
2940                 ERROR ("network plugin: malloc failed.");
2941                 return (-1);
2942         }
2943         network_init_buffer ();
2944
2945         /* setup socket(s) and so on */
2946         if (sending_sockets != NULL)
2947         {
2948                 plugin_register_write ("network", network_write,
2949                                 /* user_data = */ NULL);
2950                 plugin_register_notification ("network", network_notification,
2951                                 /* user_data = */ NULL);
2952         }
2953
2954         /* If no threads need to be started, return here. */
2955         if ((listen_sockets_num == 0)
2956                         || ((dispatch_thread_running != 0)
2957                                 && (receive_thread_running != 0)))
2958                 return (0);
2959
2960         if (dispatch_thread_running == 0)
2961         {
2962                 int status;
2963                 status = pthread_create (&dispatch_thread_id,
2964                                 NULL /* no attributes */,
2965                                 dispatch_thread,
2966                                 NULL /* no argument */);
2967                 if (status != 0)
2968                 {
2969                         char errbuf[1024];
2970                         ERROR ("network: pthread_create failed: %s",
2971                                         sstrerror (errno, errbuf,
2972                                                 sizeof (errbuf)));
2973                 }
2974                 else
2975                 {
2976                         dispatch_thread_running = 1;
2977                 }
2978         }
2979
2980         if (receive_thread_running == 0)
2981         {
2982                 int status;
2983                 status = pthread_create (&receive_thread_id,
2984                                 NULL /* no attributes */,
2985                                 receive_thread,
2986                                 NULL /* no argument */);
2987                 if (status != 0)
2988                 {
2989                         char errbuf[1024];
2990                         ERROR ("network: pthread_create failed: %s",
2991                                         sstrerror (errno, errbuf,
2992                                                 sizeof (errbuf)));
2993                 }
2994                 else
2995                 {
2996                         receive_thread_running = 1;
2997                 }
2998         }
2999
3000         return (0);
3001 } /* int network_init */
3002
3003 /* 
3004  * The flush option of the network plugin cannot flush individual identifiers.
3005  * All the values are added to a buffer and sent when the buffer is full, the
3006  * requested value may or may not be in there, it's not worth finding out. We
3007  * just send the buffer if `flush'  is called - if the requested value was in
3008  * there, good. If not, well, then there is nothing to flush.. -octo
3009  */
3010 static int network_flush (int timeout,
3011                 const char __attribute__((unused)) *identifier,
3012                 user_data_t __attribute__((unused)) *user_data)
3013 {
3014         pthread_mutex_lock (&send_buffer_lock);
3015
3016         if (send_buffer_fill > 0)
3017           flush_buffer ();
3018
3019         pthread_mutex_unlock (&send_buffer_lock);
3020
3021         return (0);
3022 } /* int network_flush */
3023
3024 void module_register (void)
3025 {
3026         plugin_register_complex_config ("network", network_config);
3027         plugin_register_init   ("network", network_init);
3028         plugin_register_flush   ("network", network_flush,
3029                         /* user_data = */ NULL);
3030 } /* void module_register */
3031
3032 /* vim: set fdm=marker : */