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                     sfree (pkg_types);
744                     sfree (pkg_values);
745                     NOTICE ("network plugin: parse_part_values: "
746                         "Don't know how to handle data source type %"PRIu8,
747                         pkg_types[i]);
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     return (-1);
1144
1145   payload_len = part_size - (PART_ENCRYPTION_AES256_SIZE + username_len);
1146   assert (payload_len > 0);
1147
1148   /* Decrypt the packet in-place */
1149   err = gcry_cipher_decrypt (cypher,
1150       buffer    + buffer_offset,
1151       part_size - buffer_offset,
1152       /* in = */ NULL, /* in len = */ 0);
1153   if (err != 0)
1154   {
1155     ERROR ("network plugin: gcry_cipher_decrypt returned: %s",
1156         gcry_strerror (err));
1157     return (-1);
1158   }
1159
1160   /* Read the hash */
1161   BUFFER_READ (pea.hash, sizeof (pea.hash));
1162
1163   /* Make sure we're at the right position - again */
1164   assert (buffer_offset == (username_len + PART_ENCRYPTION_AES256_SIZE));
1165   assert (buffer_offset == (part_size - payload_len));
1166
1167   /* Check hash sum */
1168   memset (hash, 0, sizeof (hash));
1169   gcry_md_hash_buffer (GCRY_MD_SHA1, hash,
1170       buffer + buffer_offset, payload_len);
1171   if (memcmp (hash, pea.hash, sizeof (hash)) != 0)
1172   {
1173     ERROR ("network plugin: Decryption failed: Checksum mismatch.");
1174     return (-1);
1175   }
1176
1177   parse_packet (se, buffer + buffer_offset, payload_len,
1178       flags | PP_ENCRYPTED);
1179
1180   /* Update return values */
1181   *ret_buffer =     buffer     + part_size;
1182   *ret_buffer_len = buffer_len - part_size;
1183
1184   return (0);
1185 } /* }}} int parse_part_encr_aes256 */
1186 /* #endif HAVE_LIBGCRYPT */
1187
1188 #else /* if !HAVE_LIBGCRYPT */
1189 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1190     void **ret_buffer, size_t *ret_buffer_size, int flags)
1191 {
1192   static int warning_has_been_printed = 0;
1193
1194   char *buffer;
1195   size_t buffer_size;
1196   size_t buffer_offset;
1197
1198   part_header_t ph;
1199   size_t ph_length;
1200
1201   buffer = *ret_buffer;
1202   buffer_size = *ret_buffer_size;
1203   buffer_offset = 0;
1204
1205   /* parse_packet assures this minimum size. */
1206   assert (buffer_size >= (sizeof (ph.type) + sizeof (ph.length)));
1207
1208   BUFFER_READ (&ph.type, sizeof (ph.type));
1209   BUFFER_READ (&ph.length, sizeof (ph.length));
1210   ph_length = ntohs (ph.length);
1211
1212   if ((ph_length <= PART_ENCRYPTION_AES256_SIZE)
1213       || (ph_length > buffer_size))
1214   {
1215     ERROR ("network plugin: AES-256 encrypted part "
1216         "with invalid length received.");
1217     return (-1);
1218   }
1219
1220   if (warning_has_been_printed == 0)
1221   {
1222     WARNING ("network plugin: Received encrypted packet, but the network "
1223         "plugin was not linked with libgcrypt, so I cannot "
1224         "decrypt it. The part will be discarded.");
1225     warning_has_been_printed = 1;
1226   }
1227
1228   *ret_buffer += ph_length;
1229   *ret_buffer_size -= ph_length;
1230
1231   return (0);
1232 } /* }}} int parse_part_encr_aes256 */
1233 #endif /* !HAVE_LIBGCRYPT */
1234
1235 #undef BUFFER_READ
1236
1237 static int parse_packet (sockent_t *se, /* {{{ */
1238                 void *buffer, size_t buffer_size, int flags)
1239 {
1240         int status;
1241
1242         value_list_t vl = VALUE_LIST_INIT;
1243         notification_t n;
1244
1245 #if HAVE_LIBGCRYPT
1246         int packet_was_signed = (flags & PP_SIGNED);
1247         int packet_was_encrypted = (flags & PP_ENCRYPTED);
1248         int printed_ignore_warning = 0;
1249 #endif /* HAVE_LIBGCRYPT */
1250
1251
1252         memset (&vl, '\0', sizeof (vl));
1253         memset (&n, '\0', sizeof (n));
1254         status = 0;
1255
1256         while ((status == 0) && (0 < buffer_size)
1257                         && ((unsigned int) buffer_size > sizeof (part_header_t)))
1258         {
1259                 uint16_t pkg_length;
1260                 uint16_t pkg_type;
1261
1262                 memcpy ((void *) &pkg_type,
1263                                 (void *) buffer,
1264                                 sizeof (pkg_type));
1265                 memcpy ((void *) &pkg_length,
1266                                 (void *) (buffer + sizeof (pkg_type)),
1267                                 sizeof (pkg_length));
1268
1269                 pkg_length = ntohs (pkg_length);
1270                 pkg_type = ntohs (pkg_type);
1271
1272                 if (pkg_length > buffer_size)
1273                         break;
1274                 /* Ensure that this loop terminates eventually */
1275                 if (pkg_length < (2 * sizeof (uint16_t)))
1276                         break;
1277
1278                 if (pkg_type == TYPE_ENCR_AES256)
1279                 {
1280                         status = parse_part_encr_aes256 (se,
1281                                         &buffer, &buffer_size, flags);
1282                         if (status != 0)
1283                         {
1284                                 ERROR ("network plugin: Decrypting AES256 "
1285                                                 "part failed "
1286                                                 "with status %i.", status);
1287                                 break;
1288                         }
1289                 }
1290 #if HAVE_LIBGCRYPT
1291                 else if ((se->data.server.security_level == SECURITY_LEVEL_ENCRYPT)
1292                                 && (packet_was_encrypted == 0))
1293                 {
1294                         if (printed_ignore_warning == 0)
1295                         {
1296                                 INFO ("network plugin: Unencrypted packet or "
1297                                                 "part has been ignored.");
1298                                 printed_ignore_warning = 1;
1299                         }
1300                         buffer = ((char *) buffer) + pkg_length;
1301                         continue;
1302                 }
1303 #endif /* HAVE_LIBGCRYPT */
1304                 else if (pkg_type == TYPE_SIGN_SHA256)
1305                 {
1306                         status = parse_part_sign_sha256 (se,
1307                                         &buffer, &buffer_size, flags);
1308                         if (status != 0)
1309                         {
1310                                 ERROR ("network plugin: Verifying HMAC-SHA-256 "
1311                                                 "signature failed "
1312                                                 "with status %i.", status);
1313                                 break;
1314                         }
1315                 }
1316 #if HAVE_LIBGCRYPT
1317                 else if ((se->data.server.security_level == SECURITY_LEVEL_SIGN)
1318                                 && (packet_was_encrypted == 0)
1319                                 && (packet_was_signed == 0))
1320                 {
1321                         if (printed_ignore_warning == 0)
1322                         {
1323                                 INFO ("network plugin: Unsigned packet or "
1324                                                 "part has been ignored.");
1325                                 printed_ignore_warning = 1;
1326                         }
1327                         buffer = ((char *) buffer) + pkg_length;
1328                         continue;
1329                 }
1330 #endif /* HAVE_LIBGCRYPT */
1331                 else if (pkg_type == TYPE_VALUES)
1332                 {
1333                         status = parse_part_values (&buffer, &buffer_size,
1334                                         &vl.values, &vl.values_len);
1335                         if (status != 0)
1336                                 break;
1337
1338                         network_dispatch_values (&vl);
1339
1340                         sfree (vl.values);
1341                 }
1342                 else if (pkg_type == TYPE_TIME)
1343                 {
1344                         uint64_t tmp = 0;
1345                         status = parse_part_number (&buffer, &buffer_size,
1346                                         &tmp);
1347                         if (status == 0)
1348                         {
1349                                 vl.time = (time_t) tmp;
1350                                 n.time = (time_t) tmp;
1351                         }
1352                 }
1353                 else if (pkg_type == TYPE_INTERVAL)
1354                 {
1355                         uint64_t tmp = 0;
1356                         status = parse_part_number (&buffer, &buffer_size,
1357                                         &tmp);
1358                         if (status == 0)
1359                                 vl.interval = (int) tmp;
1360                 }
1361                 else if (pkg_type == TYPE_HOST)
1362                 {
1363                         status = parse_part_string (&buffer, &buffer_size,
1364                                         vl.host, sizeof (vl.host));
1365                         if (status == 0)
1366                                 sstrncpy (n.host, vl.host, sizeof (n.host));
1367                 }
1368                 else if (pkg_type == TYPE_PLUGIN)
1369                 {
1370                         status = parse_part_string (&buffer, &buffer_size,
1371                                         vl.plugin, sizeof (vl.plugin));
1372                         if (status == 0)
1373                                 sstrncpy (n.plugin, vl.plugin,
1374                                                 sizeof (n.plugin));
1375                 }
1376                 else if (pkg_type == TYPE_PLUGIN_INSTANCE)
1377                 {
1378                         status = parse_part_string (&buffer, &buffer_size,
1379                                         vl.plugin_instance,
1380                                         sizeof (vl.plugin_instance));
1381                         if (status == 0)
1382                                 sstrncpy (n.plugin_instance,
1383                                                 vl.plugin_instance,
1384                                                 sizeof (n.plugin_instance));
1385                 }
1386                 else if (pkg_type == TYPE_TYPE)
1387                 {
1388                         status = parse_part_string (&buffer, &buffer_size,
1389                                         vl.type, sizeof (vl.type));
1390                         if (status == 0)
1391                                 sstrncpy (n.type, vl.type, sizeof (n.type));
1392                 }
1393                 else if (pkg_type == TYPE_TYPE_INSTANCE)
1394                 {
1395                         status = parse_part_string (&buffer, &buffer_size,
1396                                         vl.type_instance,
1397                                         sizeof (vl.type_instance));
1398                         if (status == 0)
1399                                 sstrncpy (n.type_instance, vl.type_instance,
1400                                                 sizeof (n.type_instance));
1401                 }
1402                 else if (pkg_type == TYPE_MESSAGE)
1403                 {
1404                         status = parse_part_string (&buffer, &buffer_size,
1405                                         n.message, sizeof (n.message));
1406
1407                         if (status != 0)
1408                         {
1409                                 /* do nothing */
1410                         }
1411                         else if ((n.severity != NOTIF_FAILURE)
1412                                         && (n.severity != NOTIF_WARNING)
1413                                         && (n.severity != NOTIF_OKAY))
1414                         {
1415                                 INFO ("network plugin: "
1416                                                 "Ignoring notification with "
1417                                                 "unknown severity %i.",
1418                                                 n.severity);
1419                         }
1420                         else if (n.time <= 0)
1421                         {
1422                                 INFO ("network plugin: "
1423                                                 "Ignoring notification with "
1424                                                 "time == 0.");
1425                         }
1426                         else if (strlen (n.message) <= 0)
1427                         {
1428                                 INFO ("network plugin: "
1429                                                 "Ignoring notification with "
1430                                                 "an empty message.");
1431                         }
1432                         else
1433                         {
1434                                 plugin_dispatch_notification (&n);
1435                         }
1436                 }
1437                 else if (pkg_type == TYPE_SEVERITY)
1438                 {
1439                         uint64_t tmp = 0;
1440                         status = parse_part_number (&buffer, &buffer_size,
1441                                         &tmp);
1442                         if (status == 0)
1443                                 n.severity = (int) tmp;
1444                 }
1445                 else
1446                 {
1447                         DEBUG ("network plugin: parse_packet: Unknown part"
1448                                         " type: 0x%04hx", pkg_type);
1449                         buffer = ((char *) buffer) + pkg_length;
1450                 }
1451         } /* while (buffer_size > sizeof (part_header_t)) */
1452
1453         if (status == 0 && buffer_size > 0)
1454                 WARNING ("network plugin: parse_packet: Received truncated "
1455                                 "packet, try increasing `MaxPacketSize'");
1456
1457         return (status);
1458 } /* }}} int parse_packet */
1459
1460 static void free_sockent_client (struct sockent_client *sec) /* {{{ */
1461 {
1462   if (sec->fd >= 0)
1463   {
1464     close (sec->fd);
1465     sec->fd = -1;
1466   }
1467   sfree (sec->addr);
1468 #if HAVE_LIBGCRYPT
1469   sfree (sec->username);
1470   sfree (sec->password);
1471   if (sec->cypher != NULL)
1472     gcry_cipher_close (sec->cypher);
1473 #endif
1474 } /* }}} void free_sockent_client */
1475
1476 static void free_sockent_server (struct sockent_server *ses) /* {{{ */
1477 {
1478   size_t i;
1479
1480   for (i = 0; i < ses->fd_num; i++)
1481   {
1482     if (ses->fd[i] >= 0)
1483     {
1484       close (ses->fd[i]);
1485       ses->fd[i] = -1;
1486     }
1487   }
1488
1489   sfree (ses->fd);
1490 #if HAVE_LIBGCRYPT
1491   sfree (ses->auth_file);
1492   fbh_destroy (ses->userdb);
1493   if (ses->cypher != NULL)
1494     gcry_cipher_close (ses->cypher);
1495 #endif
1496 } /* }}} void free_sockent_server */
1497
1498 static void sockent_destroy (sockent_t *se) /* {{{ */
1499 {
1500   sockent_t *next;
1501
1502   DEBUG ("network plugin: sockent_destroy (se = %p);", (void *) se);
1503
1504   while (se != NULL)
1505   {
1506     next = se->next;
1507
1508     sfree (se->node);
1509     sfree (se->service);
1510
1511     if (se->type == SOCKENT_TYPE_CLIENT)
1512       free_sockent_client (&se->data.client);
1513     else
1514       free_sockent_server (&se->data.server);
1515
1516     sfree (se);
1517     se = next;
1518   }
1519 } /* }}} void sockent_destroy */
1520
1521 /*
1522  * int network_set_ttl
1523  *
1524  * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
1525  * `IPV6_UNICAST_HOPS', depending on which option is applicable.
1526  *
1527  * The `struct addrinfo' is used to destinguish between unicast and multicast
1528  * sockets.
1529  */
1530 static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
1531 {
1532         DEBUG ("network plugin: network_set_ttl: network_config_ttl = %i;",
1533                         network_config_ttl);
1534
1535         assert (se->type == SOCKENT_TYPE_CLIENT);
1536
1537         if ((network_config_ttl < 1) || (network_config_ttl > 255))
1538                 return (-1);
1539
1540         if (ai->ai_family == AF_INET)
1541         {
1542                 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1543                 int optname;
1544
1545                 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1546                         optname = IP_MULTICAST_TTL;
1547                 else
1548                         optname = IP_TTL;
1549
1550                 if (setsockopt (se->data.client.fd, IPPROTO_IP, optname,
1551                                         &network_config_ttl,
1552                                         sizeof (network_config_ttl)) == -1)
1553                 {
1554                         char errbuf[1024];
1555                         ERROR ("setsockopt: %s",
1556                                         sstrerror (errno, errbuf, sizeof (errbuf)));
1557                         return (-1);
1558                 }
1559         }
1560         else if (ai->ai_family == AF_INET6)
1561         {
1562                 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1563                 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1564                 int optname;
1565
1566                 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1567                         optname = IPV6_MULTICAST_HOPS;
1568                 else
1569                         optname = IPV6_UNICAST_HOPS;
1570
1571                 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, optname,
1572                                         &network_config_ttl,
1573                                         sizeof (network_config_ttl)) == -1)
1574                 {
1575                         char errbuf[1024];
1576                         ERROR ("setsockopt: %s",
1577                                         sstrerror (errno, errbuf,
1578                                                 sizeof (errbuf)));
1579                         return (-1);
1580                 }
1581         }
1582
1583         return (0);
1584 } /* int network_set_ttl */
1585
1586 static int network_bind_socket (int fd, const struct addrinfo *ai)
1587 {
1588         int loop = 0;
1589         int yes  = 1;
1590
1591         /* allow multiple sockets to use the same PORT number */
1592         if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
1593                                 &yes, sizeof(yes)) == -1) {
1594                 char errbuf[1024];
1595                 ERROR ("setsockopt: %s", 
1596                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1597                 return (-1);
1598         }
1599
1600         DEBUG ("fd = %i; calling `bind'", fd);
1601
1602         if (bind (fd, ai->ai_addr, ai->ai_addrlen) == -1)
1603         {
1604                 char errbuf[1024];
1605                 ERROR ("bind: %s",
1606                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1607                 return (-1);
1608         }
1609
1610         if (ai->ai_family == AF_INET)
1611         {
1612                 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1613                 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1614                 {
1615                         struct ip_mreq mreq;
1616
1617                         DEBUG ("fd = %i; IPv4 multicast address found", fd);
1618
1619                         mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1620                         mreq.imr_interface.s_addr = htonl (INADDR_ANY);
1621
1622                         if (setsockopt (fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1623                                                 &loop, sizeof (loop)) == -1)
1624                         {
1625                                 char errbuf[1024];
1626                                 ERROR ("setsockopt: %s",
1627                                                 sstrerror (errno, errbuf,
1628                                                         sizeof (errbuf)));
1629                                 return (-1);
1630                         }
1631
1632                         if (setsockopt (fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1633                                                 &mreq, sizeof (mreq)) == -1)
1634                         {
1635                                 char errbuf[1024];
1636                                 ERROR ("setsockopt: %s",
1637                                                 sstrerror (errno, errbuf,
1638                                                         sizeof (errbuf)));
1639                                 return (-1);
1640                         }
1641                 }
1642         }
1643         else if (ai->ai_family == AF_INET6)
1644         {
1645                 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1646                 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1647                 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1648                 {
1649                         struct ipv6_mreq mreq;
1650
1651                         DEBUG ("fd = %i; IPv6 multicast address found", fd);
1652
1653                         memcpy (&mreq.ipv6mr_multiaddr,
1654                                         &addr->sin6_addr,
1655                                         sizeof (addr->sin6_addr));
1656
1657                         /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
1658                          * ipv6mr_interface may be set to zeroes to
1659                          * choose the default multicast interface or to
1660                          * the index of a particular multicast-capable
1661                          * interface if the host is multihomed.
1662                          * Membership is associ-associated with a
1663                          * single interface; programs running on
1664                          * multihomed hosts may need to join the same
1665                          * group on more than one interface.*/
1666                         mreq.ipv6mr_interface = 0;
1667
1668                         if (setsockopt (fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1669                                                 &loop, sizeof (loop)) == -1)
1670                         {
1671                                 char errbuf[1024];
1672                                 ERROR ("setsockopt: %s",
1673                                                 sstrerror (errno, errbuf,
1674                                                         sizeof (errbuf)));
1675                                 return (-1);
1676                         }
1677
1678                         if (setsockopt (fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
1679                                                 &mreq, sizeof (mreq)) == -1)
1680                         {
1681                                 char errbuf[1024];
1682                                 ERROR ("setsockopt: %s",
1683                                                 sstrerror (errno, errbuf,
1684                                                         sizeof (errbuf)));
1685                                 return (-1);
1686                         }
1687                 }
1688         }
1689
1690         return (0);
1691 } /* int network_bind_socket */
1692
1693 /* Initialize a sockent structure. `type' must be either `SOCKENT_TYPE_CLIENT'
1694  * or `SOCKENT_TYPE_SERVER' */
1695 static int sockent_init (sockent_t *se, int type) /* {{{ */
1696 {
1697         if (se == NULL)
1698                 return (-1);
1699
1700         memset (se, 0, sizeof (*se));
1701
1702         se->type = SOCKENT_TYPE_CLIENT;
1703         se->node = NULL;
1704         se->service = NULL;
1705         se->next = NULL;
1706
1707         if (type == SOCKENT_TYPE_SERVER)
1708         {
1709                 se->type = SOCKENT_TYPE_SERVER;
1710                 se->data.server.fd = NULL;
1711 #if HAVE_LIBGCRYPT
1712                 se->data.server.security_level = SECURITY_LEVEL_NONE;
1713                 se->data.server.auth_file = NULL;
1714                 se->data.server.userdb = NULL;
1715                 se->data.server.cypher = NULL;
1716 #endif
1717         }
1718         else
1719         {
1720                 se->data.client.fd = -1;
1721                 se->data.client.addr = NULL;
1722 #if HAVE_LIBGCRYPT
1723                 se->data.client.security_level = SECURITY_LEVEL_NONE;
1724                 se->data.client.username = NULL;
1725                 se->data.client.password = NULL;
1726                 se->data.client.cypher = NULL;
1727 #endif
1728         }
1729
1730         return (0);
1731 } /* }}} int sockent_init */
1732
1733 /* Open the file descriptors for a initialized sockent structure. */
1734 static int sockent_open (sockent_t *se) /* {{{ */
1735 {
1736         struct addrinfo  ai_hints;
1737         struct addrinfo *ai_list, *ai_ptr;
1738         int              ai_return;
1739
1740         const char *node;
1741         const char *service;
1742
1743         if (se == NULL)
1744                 return (-1);
1745
1746         /* Set up the security structures. */
1747 #if HAVE_LIBGCRYPT /* {{{ */
1748         if (se->type == SOCKENT_TYPE_CLIENT)
1749         {
1750                 if (se->data.client.security_level > SECURITY_LEVEL_NONE)
1751                 {
1752                         if ((se->data.client.username == NULL)
1753                                         || (se->data.client.password == NULL))
1754                         {
1755                                 ERROR ("network plugin: Client socket with "
1756                                                 "security requested, but no "
1757                                                 "credentials are configured.");
1758                                 return (-1);
1759                         }
1760                         gcry_md_hash_buffer (GCRY_MD_SHA256,
1761                                         se->data.client.password_hash,
1762                                         se->data.client.password,
1763                                         strlen (se->data.client.password));
1764                 }
1765         }
1766         else /* (se->type == SOCKENT_TYPE_SERVER) */
1767         {
1768                 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
1769                 {
1770                         if (se->data.server.auth_file == NULL)
1771                         {
1772                                 ERROR ("network plugin: Server socket with "
1773                                                 "security requested, but no "
1774                                                 "password file is configured.");
1775                                 return (-1);
1776                         }
1777                 }
1778                 if (se->data.server.auth_file != NULL)
1779                 {
1780                         se->data.server.userdb = fbh_create (se->data.server.auth_file);
1781                         if (se->data.server.userdb == NULL)
1782                         {
1783                                 ERROR ("network plugin: Reading password file "
1784                                                 "`%s' failed.",
1785                                                 se->data.server.auth_file);
1786                                 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
1787                                         return (-1);
1788                         }
1789                 }
1790         }
1791 #endif /* }}} HAVE_LIBGCRYPT */
1792
1793         node = se->node;
1794         service = se->service;
1795
1796         if (service == NULL)
1797           service = NET_DEFAULT_PORT;
1798
1799         DEBUG ("network plugin: sockent_open: node = %s; service = %s;",
1800             node, service);
1801
1802         memset (&ai_hints, 0, sizeof (ai_hints));
1803         ai_hints.ai_flags  = 0;
1804 #ifdef AI_PASSIVE
1805         ai_hints.ai_flags |= AI_PASSIVE;
1806 #endif
1807 #ifdef AI_ADDRCONFIG
1808         ai_hints.ai_flags |= AI_ADDRCONFIG;
1809 #endif
1810         ai_hints.ai_family   = AF_UNSPEC;
1811         ai_hints.ai_socktype = SOCK_DGRAM;
1812         ai_hints.ai_protocol = IPPROTO_UDP;
1813
1814         ai_return = getaddrinfo (node, service, &ai_hints, &ai_list);
1815         if (ai_return != 0)
1816         {
1817                 ERROR ("network plugin: getaddrinfo (%s, %s) failed: %s",
1818                                 (se->node == NULL) ? "(null)" : se->node,
1819                                 (se->service == NULL) ? "(null)" : se->service,
1820                                 gai_strerror (ai_return));
1821                 return (-1);
1822         }
1823
1824         for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1825         {
1826                 int status;
1827
1828                 if (se->type == SOCKENT_TYPE_SERVER) /* {{{ */
1829                 {
1830                         int *tmp;
1831
1832                         tmp = realloc (se->data.server.fd,
1833                                         sizeof (*tmp) * (se->data.server.fd_num + 1));
1834                         if (tmp == NULL)
1835                         {
1836                                 ERROR ("network plugin: realloc failed.");
1837                                 continue;
1838                         }
1839                         se->data.server.fd = tmp;
1840                         tmp = se->data.server.fd + se->data.server.fd_num;
1841
1842                         *tmp = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
1843                                         ai_ptr->ai_protocol);
1844                         if (*tmp < 0)
1845                         {
1846                                 char errbuf[1024];
1847                                 ERROR ("network plugin: socket(2) failed: %s",
1848                                                 sstrerror (errno, errbuf,
1849                                                         sizeof (errbuf)));
1850                                 continue;
1851                         }
1852
1853                         status = network_bind_socket (*tmp, ai_ptr);
1854                         if (status != 0)
1855                         {
1856                                 close (*tmp);
1857                                 *tmp = -1;
1858                                 continue;
1859                         }
1860
1861                         se->data.server.fd_num++;
1862                         continue;
1863                 } /* }}} if (se->type == SOCKENT_TYPE_SERVER) */
1864                 else /* if (se->type == SOCKENT_TYPE_CLIENT) {{{ */
1865                 {
1866                         se->data.client.fd = socket (ai_ptr->ai_family,
1867                                         ai_ptr->ai_socktype,
1868                                         ai_ptr->ai_protocol);
1869                         if (se->data.client.fd < 0)
1870                         {
1871                                 char errbuf[1024];
1872                                 ERROR ("network plugin: socket(2) failed: %s",
1873                                                 sstrerror (errno, errbuf,
1874                                                         sizeof (errbuf)));
1875                                 continue;
1876                         }
1877
1878                         se->data.client.addr = malloc (sizeof (*se->data.client.addr));
1879                         if (se->data.client.addr == NULL)
1880                         {
1881                                 ERROR ("network plugin: malloc failed.");
1882                                 close (se->data.client.fd);
1883                                 se->data.client.fd = -1;
1884                                 continue;
1885                         }
1886
1887                         memset (se->data.client.addr, 0, sizeof (*se->data.client.addr));
1888                         assert (sizeof (*se->data.client.addr) >= ai_ptr->ai_addrlen);
1889                         memcpy (se->data.client.addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1890                         se->data.client.addrlen = ai_ptr->ai_addrlen;
1891
1892                         network_set_ttl (se, ai_ptr);
1893
1894                         /* We don't open more than one write-socket per
1895                          * node/service pair.. */
1896                         break;
1897                 } /* }}} if (se->type == SOCKENT_TYPE_CLIENT) */
1898         } /* for (ai_list) */
1899
1900         freeaddrinfo (ai_list);
1901
1902         /* Check if all went well. */
1903         if (se->type == SOCKENT_TYPE_SERVER)
1904         {
1905                 if (se->data.server.fd_num <= 0)
1906                         return (-1);
1907         }
1908         else /* if (se->type == SOCKENT_TYPE_CLIENT) */
1909         {
1910                 if (se->data.client.fd < 0)
1911                         return (-1);
1912         }
1913
1914         return (0);
1915 } /* }}} int sockent_open */
1916
1917 /* Add a sockent to the global list of sockets */
1918 static int sockent_add (sockent_t *se) /* {{{ */
1919 {
1920         sockent_t *last_ptr;
1921
1922         if (se == NULL)
1923                 return (-1);
1924
1925         if (se->type == SOCKENT_TYPE_SERVER)
1926         {
1927                 struct pollfd *tmp;
1928                 size_t i;
1929
1930                 tmp = realloc (listen_sockets_pollfd,
1931                                 sizeof (*tmp) * (listen_sockets_num
1932                                         + se->data.server.fd_num));
1933                 if (tmp == NULL)
1934                 {
1935                         ERROR ("network plugin: realloc failed.");
1936                         return (-1);
1937                 }
1938                 listen_sockets_pollfd = tmp;
1939                 tmp = listen_sockets_pollfd + listen_sockets_num;
1940
1941                 for (i = 0; i < se->data.server.fd_num; i++)
1942                 {
1943                         memset (tmp + i, 0, sizeof (*tmp));
1944                         tmp[i].fd = se->data.server.fd[i];
1945                         tmp[i].events = POLLIN | POLLPRI;
1946                         tmp[i].revents = 0;
1947                 }
1948
1949                 listen_sockets_num += se->data.server.fd_num;
1950
1951                 if (listen_sockets == NULL)
1952                 {
1953                         listen_sockets = se;
1954                         return (0);
1955                 }
1956                 last_ptr = listen_sockets;
1957         }
1958         else /* if (se->type == SOCKENT_TYPE_CLIENT) */
1959         {
1960                 if (sending_sockets == NULL)
1961                 {
1962                         sending_sockets = se;
1963                         return (0);
1964                 }
1965                 last_ptr = sending_sockets;
1966         }
1967
1968         while (last_ptr->next != NULL)
1969                 last_ptr = last_ptr->next;
1970         last_ptr->next = se;
1971
1972         return (0);
1973 } /* }}} int sockent_add */
1974
1975 static void *dispatch_thread (void __attribute__((unused)) *arg) /* {{{ */
1976 {
1977   while (42)
1978   {
1979     receive_list_entry_t *ent;
1980     sockent_t *se;
1981
1982     /* Lock and wait for more data to come in */
1983     pthread_mutex_lock (&receive_list_lock);
1984     while ((listen_loop == 0)
1985         && (receive_list_head == NULL))
1986       pthread_cond_wait (&receive_list_cond, &receive_list_lock);
1987
1988     /* Remove the head entry and unlock */
1989     ent = receive_list_head;
1990     if (ent != NULL)
1991       receive_list_head = ent->next;
1992     receive_list_length--;
1993     pthread_mutex_unlock (&receive_list_lock);
1994
1995     /* Check whether we are supposed to exit. We do NOT check `listen_loop'
1996      * because we dispatch all missing packets before shutting down. */
1997     if (ent == NULL)
1998       break;
1999
2000     /* Look for the correct `sockent_t' */
2001     se = listen_sockets;
2002     while (se != NULL)
2003     {
2004       size_t i;
2005
2006       for (i = 0; i < se->data.server.fd_num; i++)
2007         if (se->data.server.fd[i] == ent->fd)
2008           break;
2009
2010       if (i < se->data.server.fd_num)
2011         break;
2012
2013       se = se->next;
2014     }
2015
2016     if (se == NULL)
2017     {
2018       ERROR ("network plugin: Got packet from FD %i, but can't "
2019           "find an appropriate socket entry.",
2020           ent->fd);
2021       sfree (ent->data);
2022       sfree (ent);
2023       continue;
2024     }
2025
2026     parse_packet (se, ent->data, ent->data_len, /* flags = */ 0);
2027     sfree (ent->data);
2028     sfree (ent);
2029   } /* while (42) */
2030
2031   return (NULL);
2032 } /* }}} void *dispatch_thread */
2033
2034 static int network_receive (void) /* {{{ */
2035 {
2036         char buffer[network_config_packet_size];
2037         int  buffer_len;
2038
2039         int i;
2040         int status;
2041
2042         receive_list_entry_t *private_list_head;
2043         receive_list_entry_t *private_list_tail;
2044         uint64_t              private_list_length;
2045
2046         assert (listen_sockets_num > 0);
2047
2048         private_list_head = NULL;
2049         private_list_tail = NULL;
2050         private_list_length = 0;
2051
2052         while (listen_loop == 0)
2053         {
2054                 status = poll (listen_sockets_pollfd, listen_sockets_num, -1);
2055
2056                 if (status <= 0)
2057                 {
2058                         char errbuf[1024];
2059                         if (errno == EINTR)
2060                                 continue;
2061                         ERROR ("poll failed: %s",
2062                                         sstrerror (errno, errbuf, sizeof (errbuf)));
2063                         return (-1);
2064                 }
2065
2066                 for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
2067                 {
2068                         receive_list_entry_t *ent;
2069
2070                         if ((listen_sockets_pollfd[i].revents
2071                                                 & (POLLIN | POLLPRI)) == 0)
2072                                 continue;
2073                         status--;
2074
2075                         buffer_len = recv (listen_sockets_pollfd[i].fd,
2076                                         buffer, sizeof (buffer),
2077                                         0 /* no flags */);
2078                         if (buffer_len < 0)
2079                         {
2080                                 char errbuf[1024];
2081                                 ERROR ("recv failed: %s",
2082                                                 sstrerror (errno, errbuf,
2083                                                         sizeof (errbuf)));
2084                                 return (-1);
2085                         }
2086
2087                         stats_octets_rx += ((uint64_t) buffer_len);
2088                         stats_packets_rx++;
2089
2090                         /* TODO: Possible performance enhancement: Do not free
2091                          * these entries in the dispatch thread but put them in
2092                          * another list, so we don't have to allocate more and
2093                          * more of these structures. */
2094                         ent = malloc (sizeof (receive_list_entry_t));
2095                         if (ent == NULL)
2096                         {
2097                                 ERROR ("network plugin: malloc failed.");
2098                                 return (-1);
2099                         }
2100                         memset (ent, 0, sizeof (receive_list_entry_t));
2101                         ent->data = malloc (network_config_packet_size);
2102                         if (ent->data == NULL)
2103                         {
2104                                 sfree (ent);
2105                                 ERROR ("network plugin: malloc failed.");
2106                                 return (-1);
2107                         }
2108                         ent->fd = listen_sockets_pollfd[i].fd;
2109                         ent->next = NULL;
2110
2111                         memcpy (ent->data, buffer, buffer_len);
2112                         ent->data_len = buffer_len;
2113
2114                         if (private_list_head == NULL)
2115                                 private_list_head = ent;
2116                         else
2117                                 private_list_tail->next = ent;
2118                         private_list_tail = ent;
2119                         private_list_length++;
2120
2121                         /* Do not block here. Blocking here has led to
2122                          * insufficient performance in the past. */
2123                         if (pthread_mutex_trylock (&receive_list_lock) == 0)
2124                         {
2125                                 assert (((receive_list_head == NULL) && (receive_list_length == 0))
2126                                                 || ((receive_list_head != NULL) && (receive_list_length != 0)));
2127
2128                                 if (receive_list_head == NULL)
2129                                         receive_list_head = private_list_head;
2130                                 else
2131                                         receive_list_tail->next = private_list_head;
2132                                 receive_list_tail = private_list_tail;
2133                                 receive_list_length += private_list_length;
2134
2135                                 pthread_cond_signal (&receive_list_cond);
2136                                 pthread_mutex_unlock (&receive_list_lock);
2137
2138                                 private_list_head = NULL;
2139                                 private_list_tail = NULL;
2140                                 private_list_length = 0;
2141                         }
2142                 } /* for (listen_sockets_pollfd) */
2143         } /* while (listen_loop == 0) */
2144
2145         /* Make sure everything is dispatched before exiting. */
2146         if (private_list_head != NULL)
2147         {
2148                 pthread_mutex_lock (&receive_list_lock);
2149
2150                 if (receive_list_head == NULL)
2151                         receive_list_head = private_list_head;
2152                 else
2153                         receive_list_tail->next = private_list_head;
2154                 receive_list_tail = private_list_tail;
2155                 receive_list_length += private_list_length;
2156
2157                 private_list_head = NULL;
2158                 private_list_tail = NULL;
2159                 private_list_length = 0;
2160
2161                 pthread_cond_signal (&receive_list_cond);
2162                 pthread_mutex_unlock (&receive_list_lock);
2163         }
2164
2165         return (0);
2166 } /* }}} int network_receive */
2167
2168 static void *receive_thread (void __attribute__((unused)) *arg)
2169 {
2170         return (network_receive () ? (void *) 1 : (void *) 0);
2171 } /* void *receive_thread */
2172
2173 static void network_init_buffer (void)
2174 {
2175         memset (send_buffer, 0, network_config_packet_size);
2176         send_buffer_ptr = send_buffer;
2177         send_buffer_fill = 0;
2178
2179         memset (&send_buffer_vl, 0, sizeof (send_buffer_vl));
2180 } /* int network_init_buffer */
2181
2182 static void networt_send_buffer_plain (const sockent_t *se, /* {{{ */
2183                 const char *buffer, size_t buffer_size)
2184 {
2185         int status;
2186
2187         while (42)
2188         {
2189                 status = sendto (se->data.client.fd, buffer, buffer_size,
2190                     /* flags = */ 0,
2191                     (struct sockaddr *) se->data.client.addr,
2192                     se->data.client.addrlen);
2193                 if (status < 0)
2194                 {
2195                         char errbuf[1024];
2196                         if (errno == EINTR)
2197                                 continue;
2198                         ERROR ("network plugin: sendto failed: %s",
2199                                         sstrerror (errno, errbuf,
2200                                                 sizeof (errbuf)));
2201                         break;
2202                 }
2203
2204                 break;
2205         } /* while (42) */
2206 } /* }}} void networt_send_buffer_plain */
2207
2208 #if HAVE_LIBGCRYPT
2209 #define BUFFER_ADD(p,s) do { \
2210   memcpy (buffer + buffer_offset, (p), (s)); \
2211   buffer_offset += (s); \
2212 } while (0)
2213
2214 static void networt_send_buffer_signed (const sockent_t *se, /* {{{ */
2215                 const char *in_buffer, size_t in_buffer_size)
2216 {
2217   part_signature_sha256_t ps;
2218   char buffer[BUFF_SIG_SIZE + in_buffer_size];
2219   size_t buffer_offset;
2220   size_t username_len;
2221
2222   gcry_md_hd_t hd;
2223   gcry_error_t err;
2224   unsigned char *hash;
2225
2226   hd = NULL;
2227   err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
2228   if (err != 0)
2229   {
2230     ERROR ("network plugin: Creating HMAC object failed: %s",
2231         gcry_strerror (err));
2232     return;
2233   }
2234
2235   err = gcry_md_setkey (hd, se->data.client.password,
2236       strlen (se->data.client.password));
2237   if (err != 0)
2238   {
2239     ERROR ("network plugin: gcry_md_setkey failed: %s",
2240         gcry_strerror (err));
2241     gcry_md_close (hd);
2242     return;
2243   }
2244
2245   username_len = strlen (se->data.client.username);
2246   if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE))
2247   {
2248     ERROR ("network plugin: Username too long: %s",
2249         se->data.client.username);
2250     return;
2251   }
2252
2253   memcpy (buffer + PART_SIGNATURE_SHA256_SIZE,
2254       se->data.client.username, username_len);
2255   memcpy (buffer + PART_SIGNATURE_SHA256_SIZE + username_len,
2256       in_buffer, in_buffer_size);
2257
2258   /* Initialize the `ps' structure. */
2259   memset (&ps, 0, sizeof (ps));
2260   ps.head.type = htons (TYPE_SIGN_SHA256);
2261   ps.head.length = htons (PART_SIGNATURE_SHA256_SIZE + username_len);
2262
2263   /* Calculate the hash value. */
2264   gcry_md_write (hd, buffer + PART_SIGNATURE_SHA256_SIZE,
2265       username_len + in_buffer_size);
2266   hash = gcry_md_read (hd, GCRY_MD_SHA256);
2267   if (hash == NULL)
2268   {
2269     ERROR ("network plugin: gcry_md_read failed.");
2270     gcry_md_close (hd);
2271     return;
2272   }
2273   memcpy (ps.hash, hash, sizeof (ps.hash));
2274
2275   /* Add the header */
2276   buffer_offset = 0;
2277
2278   BUFFER_ADD (&ps.head.type, sizeof (ps.head.type));
2279   BUFFER_ADD (&ps.head.length, sizeof (ps.head.length));
2280   BUFFER_ADD (ps.hash, sizeof (ps.hash));
2281
2282   assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
2283
2284   gcry_md_close (hd);
2285   hd = NULL;
2286
2287   buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
2288   networt_send_buffer_plain (se, buffer, buffer_offset);
2289 } /* }}} void networt_send_buffer_signed */
2290
2291 static void networt_send_buffer_encrypted (sockent_t *se, /* {{{ */
2292                 const char *in_buffer, size_t in_buffer_size)
2293 {
2294   part_encryption_aes256_t pea;
2295   char buffer[BUFF_SIG_SIZE + in_buffer_size];
2296   size_t buffer_size;
2297   size_t buffer_offset;
2298   size_t header_size;
2299   size_t username_len;
2300   gcry_error_t err;
2301   gcry_cipher_hd_t cypher;
2302
2303   /* Initialize the header fields */
2304   memset (&pea, 0, sizeof (pea));
2305   pea.head.type = htons (TYPE_ENCR_AES256);
2306
2307   pea.username = se->data.client.username;
2308
2309   username_len = strlen (pea.username);
2310   if ((PART_ENCRYPTION_AES256_SIZE + username_len) > BUFF_SIG_SIZE)
2311   {
2312     ERROR ("network plugin: Username too long: %s", pea.username);
2313     return;
2314   }
2315
2316   buffer_size = PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size;
2317   header_size = PART_ENCRYPTION_AES256_SIZE + username_len
2318     - sizeof (pea.hash);
2319
2320   assert (buffer_size <= sizeof (buffer));
2321   DEBUG ("network plugin: networt_send_buffer_encrypted: "
2322       "buffer_size = %zu;", buffer_size);
2323
2324   pea.head.length = htons ((uint16_t) (PART_ENCRYPTION_AES256_SIZE
2325         + username_len + in_buffer_size));
2326   pea.username_length = htons ((uint16_t) username_len);
2327
2328   /* Chose a random initialization vector. */
2329   gcry_randomize ((void *) &pea.iv, sizeof (pea.iv), GCRY_STRONG_RANDOM);
2330
2331   /* Create hash of the payload */
2332   gcry_md_hash_buffer (GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
2333
2334   /* Initialize the buffer */
2335   buffer_offset = 0;
2336   memset (buffer, 0, sizeof (buffer));
2337
2338
2339   BUFFER_ADD (&pea.head.type, sizeof (pea.head.type));
2340   BUFFER_ADD (&pea.head.length, sizeof (pea.head.length));
2341   BUFFER_ADD (&pea.username_length, sizeof (pea.username_length));
2342   BUFFER_ADD (pea.username, username_len);
2343   BUFFER_ADD (pea.iv, sizeof (pea.iv));
2344   assert (buffer_offset == header_size);
2345   BUFFER_ADD (pea.hash, sizeof (pea.hash));
2346   BUFFER_ADD (in_buffer, in_buffer_size);
2347
2348   assert (buffer_offset == buffer_size);
2349
2350   cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
2351       se->data.client.password);
2352   if (cypher == NULL)
2353     return;
2354
2355   /* Encrypt the buffer in-place */
2356   err = gcry_cipher_encrypt (cypher,
2357       buffer      + header_size,
2358       buffer_size - header_size,
2359       /* in = */ NULL, /* in len = */ 0);
2360   if (err != 0)
2361   {
2362     ERROR ("network plugin: gcry_cipher_encrypt returned: %s",
2363         gcry_strerror (err));
2364     return;
2365   }
2366
2367   /* Send it out without further modifications */
2368   networt_send_buffer_plain (se, buffer, buffer_size);
2369 } /* }}} void networt_send_buffer_encrypted */
2370 #undef BUFFER_ADD
2371 #endif /* HAVE_LIBGCRYPT */
2372
2373 static void network_send_buffer (char *buffer, size_t buffer_len) /* {{{ */
2374 {
2375   sockent_t *se;
2376
2377   DEBUG ("network plugin: network_send_buffer: buffer_len = %zu", buffer_len);
2378
2379   for (se = sending_sockets; se != NULL; se = se->next)
2380   {
2381 #if HAVE_LIBGCRYPT
2382     if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
2383       networt_send_buffer_encrypted (se, buffer, buffer_len);
2384     else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
2385       networt_send_buffer_signed (se, buffer, buffer_len);
2386     else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
2387 #endif /* HAVE_LIBGCRYPT */
2388       networt_send_buffer_plain (se, buffer, buffer_len);
2389   } /* for (sending_sockets) */
2390 } /* }}} void network_send_buffer */
2391
2392 static int add_to_buffer (char *buffer, int buffer_size, /* {{{ */
2393                 value_list_t *vl_def,
2394                 const data_set_t *ds, const value_list_t *vl)
2395 {
2396         char *buffer_orig = buffer;
2397
2398         if (strcmp (vl_def->host, vl->host) != 0)
2399         {
2400                 if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
2401                                         vl->host, strlen (vl->host)) != 0)
2402                         return (-1);
2403                 sstrncpy (vl_def->host, vl->host, sizeof (vl_def->host));
2404         }
2405
2406         if (vl_def->time != vl->time)
2407         {
2408                 if (write_part_number (&buffer, &buffer_size, TYPE_TIME,
2409                                         (uint64_t) vl->time))
2410                         return (-1);
2411                 vl_def->time = vl->time;
2412         }
2413
2414         if (vl_def->interval != vl->interval)
2415         {
2416                 if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL,
2417                                         (uint64_t) vl->interval))
2418                         return (-1);
2419                 vl_def->interval = vl->interval;
2420         }
2421
2422         if (strcmp (vl_def->plugin, vl->plugin) != 0)
2423         {
2424                 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
2425                                         vl->plugin, strlen (vl->plugin)) != 0)
2426                         return (-1);
2427                 sstrncpy (vl_def->plugin, vl->plugin, sizeof (vl_def->plugin));
2428         }
2429
2430         if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
2431         {
2432                 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
2433                                         vl->plugin_instance,
2434                                         strlen (vl->plugin_instance)) != 0)
2435                         return (-1);
2436                 sstrncpy (vl_def->plugin_instance, vl->plugin_instance, sizeof (vl_def->plugin_instance));
2437         }
2438
2439         if (strcmp (vl_def->type, vl->type) != 0)
2440         {
2441                 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
2442                                         vl->type, strlen (vl->type)) != 0)
2443                         return (-1);
2444                 sstrncpy (vl_def->type, ds->type, sizeof (vl_def->type));
2445         }
2446
2447         if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
2448         {
2449                 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
2450                                         vl->type_instance,
2451                                         strlen (vl->type_instance)) != 0)
2452                         return (-1);
2453                 sstrncpy (vl_def->type_instance, vl->type_instance, sizeof (vl_def->type_instance));
2454         }
2455         
2456         if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
2457                 return (-1);
2458
2459         return (buffer - buffer_orig);
2460 } /* }}} int add_to_buffer */
2461
2462 static void flush_buffer (void)
2463 {
2464         DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
2465                         send_buffer_fill);
2466
2467         network_send_buffer (send_buffer, (size_t) send_buffer_fill);
2468
2469         stats_octets_tx += ((uint64_t) send_buffer_fill);
2470         stats_packets_tx++;
2471
2472         network_init_buffer ();
2473 }
2474
2475 static int network_write (const data_set_t *ds, const value_list_t *vl,
2476                 user_data_t __attribute__((unused)) *user_data)
2477 {
2478         int status;
2479
2480         if (!check_send_okay (vl))
2481         {
2482 #if COLLECT_DEBUG
2483           char name[6*DATA_MAX_NAME_LEN];
2484           FORMAT_VL (name, sizeof (name), vl);
2485           name[sizeof (name) - 1] = 0;
2486           DEBUG ("network plugin: network_write: "
2487               "NOT sending %s.", name);
2488 #endif
2489           /* Counter is not protected by another lock and may be reached by
2490            * multiple threads */
2491           pthread_mutex_lock (&stats_lock);
2492           stats_values_not_sent++;
2493           pthread_mutex_unlock (&stats_lock);
2494           return (0);
2495         }
2496
2497         uc_meta_data_add_unsigned_int (vl,
2498             "network:time_sent", (uint64_t) vl->time);
2499
2500         pthread_mutex_lock (&send_buffer_lock);
2501
2502         status = add_to_buffer (send_buffer_ptr,
2503                         network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2504                         &send_buffer_vl,
2505                         ds, vl);
2506         if (status >= 0)
2507         {
2508                 /* status == bytes added to the buffer */
2509                 send_buffer_fill += status;
2510                 send_buffer_ptr  += status;
2511
2512                 stats_values_sent++;
2513         }
2514         else
2515         {
2516                 flush_buffer ();
2517
2518                 status = add_to_buffer (send_buffer_ptr,
2519                                 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2520                                 &send_buffer_vl,
2521                                 ds, vl);
2522
2523                 if (status >= 0)
2524                 {
2525                         send_buffer_fill += status;
2526                         send_buffer_ptr  += status;
2527
2528                         stats_values_sent++;
2529                 }
2530         }
2531
2532         if (status < 0)
2533         {
2534                 ERROR ("network plugin: Unable to append to the "
2535                                 "buffer for some weird reason");
2536         }
2537         else if ((network_config_packet_size - send_buffer_fill) < 15)
2538         {
2539                 flush_buffer ();
2540         }
2541
2542         pthread_mutex_unlock (&send_buffer_lock);
2543
2544         return ((status < 0) ? -1 : 0);
2545 } /* int network_write */
2546
2547 static int network_config_set_boolean (const oconfig_item_t *ci, /* {{{ */
2548     int *retval)
2549 {
2550   if ((ci->values_num != 1)
2551       || ((ci->values[0].type != OCONFIG_TYPE_BOOLEAN)
2552         && (ci->values[0].type != OCONFIG_TYPE_STRING)))
2553   {
2554     ERROR ("network plugin: The `%s' config option needs "
2555         "exactly one boolean argument.", ci->key);
2556     return (-1);
2557   }
2558
2559   if (ci->values[0].type == OCONFIG_TYPE_BOOLEAN)
2560   {
2561     if (ci->values[0].value.boolean)
2562       *retval = 1;
2563     else
2564       *retval = 0;
2565   }
2566   else
2567   {
2568     char *str = ci->values[0].value.string;
2569
2570     if (IS_TRUE (str))
2571       *retval = 1;
2572     else if (IS_FALSE (str))
2573       *retval = 0;
2574     else
2575     {
2576       ERROR ("network plugin: Cannot parse string value `%s' of the `%s' "
2577           "option as boolean value.",
2578           str, ci->key);
2579       return (-1);
2580     }
2581   }
2582
2583   return (0);
2584 } /* }}} int network_config_set_boolean */
2585
2586 static int network_config_set_ttl (const oconfig_item_t *ci) /* {{{ */
2587 {
2588   int tmp;
2589   if ((ci->values_num != 1)
2590       || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2591   {
2592     WARNING ("network plugin: The `TimeToLive' config option needs exactly "
2593         "one numeric argument.");
2594     return (-1);
2595   }
2596
2597   tmp = (int) ci->values[0].value.number;
2598   if ((tmp > 0) && (tmp <= 255))
2599     network_config_ttl = tmp;
2600
2601   return (0);
2602 } /* }}} int network_config_set_ttl */
2603
2604 static int network_config_set_buffer_size (const oconfig_item_t *ci) /* {{{ */
2605 {
2606   int tmp;
2607   if ((ci->values_num != 1)
2608       || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2609   {
2610     WARNING ("network plugin: The `MaxPacketSize' config option needs exactly "
2611         "one numeric argument.");
2612     return (-1);
2613   }
2614
2615   tmp = (int) ci->values[0].value.number;
2616   if ((tmp >= 1024) && (tmp <= 65535))
2617     network_config_packet_size = tmp;
2618
2619   return (0);
2620 } /* }}} int network_config_set_buffer_size */
2621
2622 #if HAVE_LIBGCRYPT
2623 static int network_config_set_string (const oconfig_item_t *ci, /* {{{ */
2624     char **ret_string)
2625 {
2626   char *tmp;
2627   if ((ci->values_num != 1)
2628       || (ci->values[0].type != OCONFIG_TYPE_STRING))
2629   {
2630     WARNING ("network plugin: The `%s' config option needs exactly "
2631         "one string argument.", ci->key);
2632     return (-1);
2633   }
2634
2635   tmp = strdup (ci->values[0].value.string);
2636   if (tmp == NULL)
2637     return (-1);
2638
2639   sfree (*ret_string);
2640   *ret_string = tmp;
2641
2642   return (0);
2643 } /* }}} int network_config_set_string */
2644 #endif /* HAVE_LIBGCRYPT */
2645
2646 #if HAVE_LIBGCRYPT
2647 static int network_config_set_security_level (oconfig_item_t *ci, /* {{{ */
2648     int *retval)
2649 {
2650   char *str;
2651   if ((ci->values_num != 1)
2652       || (ci->values[0].type != OCONFIG_TYPE_STRING))
2653   {
2654     WARNING ("network plugin: The `SecurityLevel' config option needs exactly "
2655         "one string argument.");
2656     return (-1);
2657   }
2658
2659   str = ci->values[0].value.string;
2660   if (strcasecmp ("Encrypt", str) == 0)
2661     *retval = SECURITY_LEVEL_ENCRYPT;
2662   else if (strcasecmp ("Sign", str) == 0)
2663     *retval = SECURITY_LEVEL_SIGN;
2664   else if (strcasecmp ("None", str) == 0)
2665     *retval = SECURITY_LEVEL_NONE;
2666   else
2667   {
2668     WARNING ("network plugin: Unknown security level: %s.", str);
2669     return (-1);
2670   }
2671
2672   return (0);
2673 } /* }}} int network_config_set_security_level */
2674 #endif /* HAVE_LIBGCRYPT */
2675
2676 static int network_config_add_listen (const oconfig_item_t *ci) /* {{{ */
2677 {
2678   sockent_t *se;
2679   int status;
2680   int i;
2681
2682   if ((ci->values_num < 1) || (ci->values_num > 2)
2683       || (ci->values[0].type != OCONFIG_TYPE_STRING)
2684       || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
2685   {
2686     ERROR ("network plugin: The `%s' config option needs "
2687         "one or two string arguments.", ci->key);
2688     return (-1);
2689   }
2690
2691   se = malloc (sizeof (*se));
2692   if (se == NULL)
2693   {
2694     ERROR ("network plugin: malloc failed.");
2695     return (-1);
2696   }
2697   sockent_init (se, SOCKENT_TYPE_SERVER);
2698
2699   se->node = strdup (ci->values[0].value.string);
2700   if (ci->values_num >= 2)
2701     se->service = strdup (ci->values[1].value.string);
2702
2703   for (i = 0; i < ci->children_num; i++)
2704   {
2705     oconfig_item_t *child = ci->children + i;
2706
2707 #if HAVE_LIBGCRYPT
2708     if (strcasecmp ("AuthFile", child->key) == 0)
2709       network_config_set_string (child, &se->data.server.auth_file);
2710     else if (strcasecmp ("SecurityLevel", child->key) == 0)
2711       network_config_set_security_level (child,
2712           &se->data.server.security_level);
2713     else
2714 #endif /* HAVE_LIBGCRYPT */
2715     {
2716       WARNING ("network plugin: Option `%s' is not allowed here.",
2717           child->key);
2718     }
2719   }
2720
2721 #if HAVE_LIBGCRYPT
2722   if ((se->data.server.security_level > SECURITY_LEVEL_NONE)
2723       && (se->data.server.auth_file == NULL))
2724   {
2725     ERROR ("network plugin: A security level higher than `none' was "
2726         "requested, but no AuthFile option was given. Cowardly refusing to "
2727         "open this socket!");
2728     sockent_destroy (se);
2729     return (-1);
2730   }
2731 #endif /* HAVE_LIBGCRYPT */
2732
2733   status = sockent_open (se);
2734   if (status != 0)
2735   {
2736     ERROR ("network plugin: network_config_add_listen: sockent_open failed.");
2737     sockent_destroy (se);
2738     return (-1);
2739   }
2740
2741   status = sockent_add (se);
2742   if (status != 0)
2743   {
2744     ERROR ("network plugin: network_config_add_listen: sockent_add failed.");
2745     sockent_destroy (se);
2746     return (-1);
2747   }
2748
2749   return (0);
2750 } /* }}} int network_config_add_listen */
2751
2752 static int network_config_add_server (const oconfig_item_t *ci) /* {{{ */
2753 {
2754   sockent_t *se;
2755   int status;
2756   int i;
2757
2758   if ((ci->values_num < 1) || (ci->values_num > 2)
2759       || (ci->values[0].type != OCONFIG_TYPE_STRING)
2760       || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
2761   {
2762     ERROR ("network plugin: The `%s' config option needs "
2763         "one or two string arguments.", ci->key);
2764     return (-1);
2765   }
2766
2767   se = malloc (sizeof (*se));
2768   if (se == NULL)
2769   {
2770     ERROR ("network plugin: malloc failed.");
2771     return (-1);
2772   }
2773   sockent_init (se, SOCKENT_TYPE_CLIENT);
2774
2775   se->node = strdup (ci->values[0].value.string);
2776   if (ci->values_num >= 2)
2777     se->service = strdup (ci->values[1].value.string);
2778
2779   for (i = 0; i < ci->children_num; i++)
2780   {
2781     oconfig_item_t *child = ci->children + i;
2782
2783 #if HAVE_LIBGCRYPT
2784     if (strcasecmp ("Username", child->key) == 0)
2785       network_config_set_string (child, &se->data.client.username);
2786     else if (strcasecmp ("Password", child->key) == 0)
2787       network_config_set_string (child, &se->data.client.password);
2788     else if (strcasecmp ("SecurityLevel", child->key) == 0)
2789       network_config_set_security_level (child,
2790           &se->data.client.security_level);
2791     else
2792 #endif /* HAVE_LIBGCRYPT */
2793     {
2794       WARNING ("network plugin: Option `%s' is not allowed here.",
2795           child->key);
2796     }
2797   }
2798
2799 #if HAVE_LIBGCRYPT
2800   if ((se->data.client.security_level > SECURITY_LEVEL_NONE)
2801       && ((se->data.client.username == NULL)
2802         || (se->data.client.password == NULL)))
2803   {
2804     ERROR ("network plugin: A security level higher than `none' was "
2805         "requested, but no Username or Password option was given. "
2806         "Cowardly refusing to open this socket!");
2807     sockent_destroy (se);
2808     return (-1);
2809   }
2810 #endif /* HAVE_LIBGCRYPT */
2811
2812   status = sockent_open (se);
2813   if (status != 0)
2814   {
2815     ERROR ("network plugin: network_config_add_server: sockent_open failed.");
2816     sockent_destroy (se);
2817     return (-1);
2818   }
2819
2820   status = sockent_add (se);
2821   if (status != 0)
2822   {
2823     ERROR ("network plugin: network_config_add_server: sockent_add failed.");
2824     sockent_destroy (se);
2825     return (-1);
2826   }
2827
2828   return (0);
2829 } /* }}} int network_config_add_server */
2830
2831 static int network_config (oconfig_item_t *ci) /* {{{ */
2832 {
2833   int i;
2834
2835   for (i = 0; i < ci->children_num; i++)
2836   {
2837     oconfig_item_t *child = ci->children + i;
2838
2839     if (strcasecmp ("Listen", child->key) == 0)
2840       network_config_add_listen (child);
2841     else if (strcasecmp ("Server", child->key) == 0)
2842       network_config_add_server (child);
2843     else if (strcasecmp ("TimeToLive", child->key) == 0)
2844       network_config_set_ttl (child);
2845     else if (strcasecmp ("MaxPacketSize", child->key) == 0)
2846       network_config_set_buffer_size (child);
2847     else if (strcasecmp ("Forward", child->key) == 0)
2848       network_config_set_boolean (child, &network_config_forward);
2849     else if (strcasecmp ("ReportStats", child->key) == 0)
2850       network_config_set_boolean (child, &network_config_stats);
2851     else if (strcasecmp ("CacheFlush", child->key) == 0)
2852       /* no op for backwards compatibility only */;
2853     else
2854     {
2855       WARNING ("network plugin: Option `%s' is not allowed here.",
2856           child->key);
2857     }
2858   }
2859
2860   return (0);
2861 } /* }}} int network_config */
2862
2863 static int network_notification (const notification_t *n,
2864                 user_data_t __attribute__((unused)) *user_data)
2865 {
2866   char  buffer[network_config_packet_size];
2867   char *buffer_ptr = buffer;
2868   int   buffer_free = sizeof (buffer);
2869   int   status;
2870
2871   memset (buffer, '\0', sizeof (buffer));
2872
2873
2874   status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME,
2875       (uint64_t) n->time);
2876   if (status != 0)
2877     return (-1);
2878
2879   status = write_part_number (&buffer_ptr, &buffer_free, TYPE_SEVERITY,
2880       (uint64_t) n->severity);
2881   if (status != 0)
2882     return (-1);
2883
2884   if (strlen (n->host) > 0)
2885   {
2886     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_HOST,
2887         n->host, strlen (n->host));
2888     if (status != 0)
2889       return (-1);
2890   }
2891
2892   if (strlen (n->plugin) > 0)
2893   {
2894     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_PLUGIN,
2895         n->plugin, strlen (n->plugin));
2896     if (status != 0)
2897       return (-1);
2898   }
2899
2900   if (strlen (n->plugin_instance) > 0)
2901   {
2902     status = write_part_string (&buffer_ptr, &buffer_free,
2903         TYPE_PLUGIN_INSTANCE,
2904         n->plugin_instance, strlen (n->plugin_instance));
2905     if (status != 0)
2906       return (-1);
2907   }
2908
2909   if (strlen (n->type) > 0)
2910   {
2911     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE,
2912         n->type, strlen (n->type));
2913     if (status != 0)
2914       return (-1);
2915   }
2916
2917   if (strlen (n->type_instance) > 0)
2918   {
2919     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
2920         n->type_instance, strlen (n->type_instance));
2921     if (status != 0)
2922       return (-1);
2923   }
2924
2925   status = write_part_string (&buffer_ptr, &buffer_free, TYPE_MESSAGE,
2926       n->message, strlen (n->message));
2927   if (status != 0)
2928     return (-1);
2929
2930   network_send_buffer (buffer, sizeof (buffer) - buffer_free);
2931
2932   return (0);
2933 } /* int network_notification */
2934
2935 static int network_shutdown (void)
2936 {
2937         listen_loop++;
2938
2939         /* Kill the listening thread */
2940         if (receive_thread_running != 0)
2941         {
2942                 INFO ("network plugin: Stopping receive thread.");
2943                 pthread_kill (receive_thread_id, SIGTERM);
2944                 pthread_join (receive_thread_id, NULL /* no return value */);
2945                 memset (&receive_thread_id, 0, sizeof (receive_thread_id));
2946                 receive_thread_running = 0;
2947         }
2948
2949         /* Shutdown the dispatching thread */
2950         if (dispatch_thread_running != 0)
2951         {
2952                 INFO ("network plugin: Stopping dispatch thread.");
2953                 pthread_mutex_lock (&receive_list_lock);
2954                 pthread_cond_broadcast (&receive_list_cond);
2955                 pthread_mutex_unlock (&receive_list_lock);
2956                 pthread_join (dispatch_thread_id, /* ret = */ NULL);
2957                 dispatch_thread_running = 0;
2958         }
2959
2960         sockent_destroy (listen_sockets);
2961
2962         if (send_buffer_fill > 0)
2963                 flush_buffer ();
2964
2965         sfree (send_buffer);
2966
2967         /* TODO: Close `sending_sockets' */
2968
2969         plugin_unregister_config ("network");
2970         plugin_unregister_init ("network");
2971         plugin_unregister_write ("network");
2972         plugin_unregister_shutdown ("network");
2973
2974         return (0);
2975 } /* int network_shutdown */
2976
2977 static int network_stats_read (void) /* {{{ */
2978 {
2979         uint64_t copy_octets_rx;
2980         uint64_t copy_octets_tx;
2981         uint64_t copy_packets_rx;
2982         uint64_t copy_packets_tx;
2983         uint64_t copy_values_dispatched;
2984         uint64_t copy_values_not_dispatched;
2985         uint64_t copy_values_sent;
2986         uint64_t copy_values_not_sent;
2987         uint64_t copy_receive_list_length;
2988         value_list_t vl = VALUE_LIST_INIT;
2989         value_t values[2];
2990
2991         copy_octets_rx = stats_octets_rx;
2992         copy_octets_tx = stats_octets_tx;
2993         copy_packets_rx = stats_packets_rx;
2994         copy_packets_tx = stats_packets_tx;
2995         copy_values_dispatched = stats_values_dispatched;
2996         copy_values_not_dispatched = stats_values_not_dispatched;
2997         copy_values_sent = stats_values_sent;
2998         copy_values_not_sent = stats_values_not_sent;
2999         copy_receive_list_length = receive_list_length;
3000
3001         /* Initialize `vl' */
3002         vl.values = values;
3003         vl.values_len = 2;
3004         vl.time = 0;
3005         vl.interval = interval_g;
3006         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
3007         sstrncpy (vl.plugin, "network", sizeof (vl.plugin));
3008
3009         /* Octets received / sent */
3010         vl.values[0].counter = (counter_t) copy_octets_rx;
3011         vl.values[1].counter = (counter_t) copy_octets_tx;
3012         sstrncpy (vl.type, "if_octets", sizeof (vl.type));
3013         plugin_dispatch_values (&vl);
3014
3015         /* Packets received / send */
3016         vl.values[0].counter = (counter_t) copy_packets_rx;
3017         vl.values[1].counter = (counter_t) copy_packets_tx;
3018         sstrncpy (vl.type, "if_packets", sizeof (vl.type));
3019         plugin_dispatch_values (&vl);
3020
3021         /* Values (not) dispatched and (not) send */
3022         sstrncpy (vl.type, "total_values", sizeof (vl.type));
3023         vl.values_len = 1;
3024
3025         vl.values[0].derive = (derive_t) copy_values_dispatched;
3026         sstrncpy (vl.type_instance, "dispatch-accepted",
3027                         sizeof (vl.type_instance));
3028         plugin_dispatch_values (&vl);
3029
3030         vl.values[0].derive = (derive_t) copy_values_not_dispatched;
3031         sstrncpy (vl.type_instance, "dispatch-rejected",
3032                         sizeof (vl.type_instance));
3033         plugin_dispatch_values (&vl);
3034
3035         vl.values[0].derive = (derive_t) copy_values_sent;
3036         sstrncpy (vl.type_instance, "send-accepted",
3037                         sizeof (vl.type_instance));
3038         plugin_dispatch_values (&vl);
3039
3040         vl.values[0].derive = (derive_t) copy_values_not_sent;
3041         sstrncpy (vl.type_instance, "send-rejected",
3042                         sizeof (vl.type_instance));
3043         plugin_dispatch_values (&vl);
3044
3045         /* Receive queue length */
3046         vl.values[0].gauge = (gauge_t) copy_receive_list_length;
3047         sstrncpy (vl.type, "queue_length", sizeof (vl.type));
3048         vl.type_instance[0] = 0;
3049         plugin_dispatch_values (&vl);
3050
3051         return (0);
3052 } /* }}} int network_stats_read */
3053
3054 static int network_init (void)
3055 {
3056         static _Bool have_init = false;
3057
3058         /* Check if we were already initialized. If so, just return - there's
3059          * nothing more to do (for now, that is). */
3060         if (have_init)
3061                 return (0);
3062         have_init = true;
3063
3064 #if HAVE_LIBGCRYPT
3065         gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
3066         gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
3067         gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
3068 #endif
3069
3070         if (network_config_stats != 0)
3071                 plugin_register_read ("network", network_stats_read);
3072
3073         plugin_register_shutdown ("network", network_shutdown);
3074
3075         send_buffer = malloc (network_config_packet_size);
3076         if (send_buffer == NULL)
3077         {
3078                 ERROR ("network plugin: malloc failed.");
3079                 return (-1);
3080         }
3081         network_init_buffer ();
3082
3083         /* setup socket(s) and so on */
3084         if (sending_sockets != NULL)
3085         {
3086                 plugin_register_write ("network", network_write,
3087                                 /* user_data = */ NULL);
3088                 plugin_register_notification ("network", network_notification,
3089                                 /* user_data = */ NULL);
3090         }
3091
3092         /* If no threads need to be started, return here. */
3093         if ((listen_sockets_num == 0)
3094                         || ((dispatch_thread_running != 0)
3095                                 && (receive_thread_running != 0)))
3096                 return (0);
3097
3098         if (dispatch_thread_running == 0)
3099         {
3100                 int status;
3101                 status = pthread_create (&dispatch_thread_id,
3102                                 NULL /* no attributes */,
3103                                 dispatch_thread,
3104                                 NULL /* no argument */);
3105                 if (status != 0)
3106                 {
3107                         char errbuf[1024];
3108                         ERROR ("network: pthread_create failed: %s",
3109                                         sstrerror (errno, errbuf,
3110                                                 sizeof (errbuf)));
3111                 }
3112                 else
3113                 {
3114                         dispatch_thread_running = 1;
3115                 }
3116         }
3117
3118         if (receive_thread_running == 0)
3119         {
3120                 int status;
3121                 status = pthread_create (&receive_thread_id,
3122                                 NULL /* no attributes */,
3123                                 receive_thread,
3124                                 NULL /* no argument */);
3125                 if (status != 0)
3126                 {
3127                         char errbuf[1024];
3128                         ERROR ("network: pthread_create failed: %s",
3129                                         sstrerror (errno, errbuf,
3130                                                 sizeof (errbuf)));
3131                 }
3132                 else
3133                 {
3134                         receive_thread_running = 1;
3135                 }
3136         }
3137
3138         return (0);
3139 } /* int network_init */
3140
3141 /* 
3142  * The flush option of the network plugin cannot flush individual identifiers.
3143  * All the values are added to a buffer and sent when the buffer is full, the
3144  * requested value may or may not be in there, it's not worth finding out. We
3145  * just send the buffer if `flush'  is called - if the requested value was in
3146  * there, good. If not, well, then there is nothing to flush.. -octo
3147  */
3148 static int network_flush (int timeout,
3149                 const char __attribute__((unused)) *identifier,
3150                 user_data_t __attribute__((unused)) *user_data)
3151 {
3152         pthread_mutex_lock (&send_buffer_lock);
3153
3154         if (send_buffer_fill > 0)
3155           flush_buffer ();
3156
3157         pthread_mutex_unlock (&send_buffer_lock);
3158
3159         return (0);
3160 } /* int network_flush */
3161
3162 void module_register (void)
3163 {
3164         plugin_register_complex_config ("network", network_config);
3165         plugin_register_init   ("network", network_init);
3166         plugin_register_flush   ("network", network_flush,
3167                         /* user_data = */ NULL);
3168 } /* void module_register */
3169
3170 /* vim: set fdm=marker : */