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