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