Proposal fix for large "MaxPacketSize" use.
[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_secure (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 < 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 < 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 < 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 (se->interface != 0)
1687         {
1688 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
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 /* #endif HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1706
1707 #else
1708                 WARNING ("network plugin: Cannot set the interface on a unicast "
1709                         "socket because "
1710 # if !defined(SO_BINDTODEVICE)
1711                         "the \"SO_BINDTODEVICE\" socket option "
1712 # else
1713                         "the \"if_indextoname\" function "
1714 # endif
1715                         "is not available on your system.");
1716 #endif
1717
1718         }
1719
1720         return (0);
1721 } /* }}} network_set_interface */
1722
1723 static int network_bind_socket (int fd, const struct addrinfo *ai, const int interface_idx)
1724 {
1725         int loop = 0;
1726         int yes  = 1;
1727
1728         /* allow multiple sockets to use the same PORT number */
1729         if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
1730                                 &yes, sizeof(yes)) == -1) {
1731                 char errbuf[1024];
1732                 ERROR ("setsockopt: %s", 
1733                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1734                 return (-1);
1735         }
1736
1737         DEBUG ("fd = %i; calling `bind'", fd);
1738
1739         if (bind (fd, ai->ai_addr, ai->ai_addrlen) == -1)
1740         {
1741                 char errbuf[1024];
1742                 ERROR ("bind: %s",
1743                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1744                 return (-1);
1745         }
1746
1747         if (ai->ai_family == AF_INET)
1748         {
1749                 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1750                 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1751                 {
1752 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1753                         struct ip_mreqn mreq;
1754 #else
1755                         struct ip_mreq mreq;
1756 #endif
1757
1758                         DEBUG ("fd = %i; IPv4 multicast address found", fd);
1759
1760                         mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1761 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1762                         /* Set the interface using the interface index if
1763                          * possible (available). Unfortunately, the struct
1764                          * ip_mreqn is not portable. */
1765                         mreq.imr_address.s_addr = ntohl (INADDR_ANY);
1766                         mreq.imr_ifindex = interface_idx;
1767 #else
1768                         mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
1769 #endif
1770
1771                         if (setsockopt (fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1772                                                 &loop, sizeof (loop)) == -1)
1773                         {
1774                                 char errbuf[1024];
1775                                 ERROR ("setsockopt: %s",
1776                                                 sstrerror (errno, errbuf,
1777                                                         sizeof (errbuf)));
1778                                 return (-1);
1779                         }
1780
1781                         if (setsockopt (fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1782                                                 &mreq, sizeof (mreq)) == -1)
1783                         {
1784                                 char errbuf[1024];
1785                                 ERROR ("setsockopt: %s",
1786                                                 sstrerror (errno, errbuf,
1787                                                         sizeof (errbuf)));
1788                                 return (-1);
1789                         }
1790
1791                         return (0);
1792                 }
1793         }
1794         else if (ai->ai_family == AF_INET6)
1795         {
1796                 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1797                 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1798                 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1799                 {
1800                         struct ipv6_mreq mreq;
1801
1802                         DEBUG ("fd = %i; IPv6 multicast address found", fd);
1803
1804                         memcpy (&mreq.ipv6mr_multiaddr,
1805                                         &addr->sin6_addr,
1806                                         sizeof (addr->sin6_addr));
1807
1808                         /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
1809                          * ipv6mr_interface may be set to zeroes to
1810                          * choose the default multicast interface or to
1811                          * the index of a particular multicast-capable
1812                          * interface if the host is multihomed.
1813                          * Membership is associ-associated with a
1814                          * single interface; programs running on
1815                          * multihomed hosts may need to join the same
1816                          * group on more than one interface.*/
1817                         mreq.ipv6mr_interface = interface_idx;
1818
1819                         if (setsockopt (fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1820                                                 &loop, sizeof (loop)) == -1)
1821                         {
1822                                 char errbuf[1024];
1823                                 ERROR ("setsockopt: %s",
1824                                                 sstrerror (errno, errbuf,
1825                                                         sizeof (errbuf)));
1826                                 return (-1);
1827                         }
1828
1829                         if (setsockopt (fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
1830                                                 &mreq, sizeof (mreq)) == -1)
1831                         {
1832                                 char errbuf[1024];
1833                                 ERROR ("setsockopt: %s",
1834                                                 sstrerror (errno, errbuf,
1835                                                         sizeof (errbuf)));
1836                                 return (-1);
1837                         }
1838
1839                         return (0);
1840                 }
1841         }
1842
1843 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1844         /* if a specific interface was set, bind the socket to it. But to avoid
1845          * possible problems with multicast routing, only do that for non-multicast
1846          * addresses */
1847         if (interface_idx != 0)
1848         {
1849                 char interface_name[IFNAMSIZ];
1850
1851                 if (if_indextoname (interface_idx, interface_name) == NULL)
1852                         return (-1);
1853
1854                 DEBUG ("fd = %i; Binding socket to interface %s", fd, interface_name);
1855
1856                 if (setsockopt (fd, SOL_SOCKET, SO_BINDTODEVICE,
1857                                         interface_name,
1858                                         sizeof(interface_name)) == -1 )
1859                 {
1860                         char errbuf[1024];
1861                         ERROR ("setsockopt: %s",
1862                                         sstrerror (errno, errbuf, sizeof (errbuf)));
1863                         return (-1);
1864                 }
1865         }
1866 #endif /* HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1867
1868         return (0);
1869 } /* int network_bind_socket */
1870
1871 /* Initialize a sockent structure. `type' must be either `SOCKENT_TYPE_CLIENT'
1872  * or `SOCKENT_TYPE_SERVER' */
1873 static int sockent_init (sockent_t *se, int type) /* {{{ */
1874 {
1875         if (se == NULL)
1876                 return (-1);
1877
1878         memset (se, 0, sizeof (*se));
1879
1880         se->type = SOCKENT_TYPE_CLIENT;
1881         se->node = NULL;
1882         se->service = NULL;
1883         se->interface = 0;
1884         se->next = NULL;
1885
1886         if (type == SOCKENT_TYPE_SERVER)
1887         {
1888                 se->type = SOCKENT_TYPE_SERVER;
1889                 se->data.server.fd = NULL;
1890 #if HAVE_LIBGCRYPT
1891                 se->data.server.security_level = SECURITY_LEVEL_NONE;
1892                 se->data.server.auth_file = NULL;
1893                 se->data.server.userdb = NULL;
1894                 se->data.server.cypher = NULL;
1895 #endif
1896         }
1897         else
1898         {
1899                 se->data.client.fd = -1;
1900                 se->data.client.addr = NULL;
1901 #if HAVE_LIBGCRYPT
1902                 se->data.client.security_level = SECURITY_LEVEL_NONE;
1903                 se->data.client.username = NULL;
1904                 se->data.client.password = NULL;
1905                 se->data.client.cypher = NULL;
1906 #endif
1907         }
1908
1909         return (0);
1910 } /* }}} int sockent_init */
1911
1912 /* Open the file descriptors for a initialized sockent structure. */
1913 static int sockent_open (sockent_t *se) /* {{{ */
1914 {
1915         struct addrinfo  ai_hints;
1916         struct addrinfo *ai_list, *ai_ptr;
1917         int              ai_return;
1918
1919         const char *node;
1920         const char *service;
1921
1922         if (se == NULL)
1923                 return (-1);
1924
1925         /* Set up the security structures. */
1926 #if HAVE_LIBGCRYPT /* {{{ */
1927         if (se->type == SOCKENT_TYPE_CLIENT)
1928         {
1929                 if (se->data.client.security_level > SECURITY_LEVEL_NONE)
1930                 {
1931                         if ((se->data.client.username == NULL)
1932                                         || (se->data.client.password == NULL))
1933                         {
1934                                 ERROR ("network plugin: Client socket with "
1935                                                 "security requested, but no "
1936                                                 "credentials are configured.");
1937                                 return (-1);
1938                         }
1939                         gcry_md_hash_buffer (GCRY_MD_SHA256,
1940                                         se->data.client.password_hash,
1941                                         se->data.client.password,
1942                                         strlen (se->data.client.password));
1943                 }
1944         }
1945         else /* (se->type == SOCKENT_TYPE_SERVER) */
1946         {
1947                 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
1948                 {
1949                         if (se->data.server.auth_file == NULL)
1950                         {
1951                                 ERROR ("network plugin: Server socket with "
1952                                                 "security requested, but no "
1953                                                 "password file is configured.");
1954                                 return (-1);
1955                         }
1956                 }
1957                 if (se->data.server.auth_file != NULL)
1958                 {
1959                         se->data.server.userdb = fbh_create (se->data.server.auth_file);
1960                         if (se->data.server.userdb == NULL)
1961                         {
1962                                 ERROR ("network plugin: Reading password file "
1963                                                 "`%s' failed.",
1964                                                 se->data.server.auth_file);
1965                                 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
1966                                         return (-1);
1967                         }
1968                 }
1969         }
1970 #endif /* }}} HAVE_LIBGCRYPT */
1971
1972         node = se->node;
1973         service = se->service;
1974
1975         if (service == NULL)
1976           service = NET_DEFAULT_PORT;
1977
1978         DEBUG ("network plugin: sockent_open: node = %s; service = %s;",
1979             node, service);
1980
1981         memset (&ai_hints, 0, sizeof (ai_hints));
1982         ai_hints.ai_flags  = 0;
1983 #ifdef AI_PASSIVE
1984         ai_hints.ai_flags |= AI_PASSIVE;
1985 #endif
1986 #ifdef AI_ADDRCONFIG
1987         ai_hints.ai_flags |= AI_ADDRCONFIG;
1988 #endif
1989         ai_hints.ai_family   = AF_UNSPEC;
1990         ai_hints.ai_socktype = SOCK_DGRAM;
1991         ai_hints.ai_protocol = IPPROTO_UDP;
1992
1993         ai_return = getaddrinfo (node, service, &ai_hints, &ai_list);
1994         if (ai_return != 0)
1995         {
1996                 ERROR ("network plugin: getaddrinfo (%s, %s) failed: %s",
1997                                 (se->node == NULL) ? "(null)" : se->node,
1998                                 (se->service == NULL) ? "(null)" : se->service,
1999                                 gai_strerror (ai_return));
2000                 return (-1);
2001         }
2002
2003         for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
2004         {
2005                 int status;
2006
2007                 if (se->type == SOCKENT_TYPE_SERVER) /* {{{ */
2008                 {
2009                         int *tmp;
2010
2011                         tmp = realloc (se->data.server.fd,
2012                                         sizeof (*tmp) * (se->data.server.fd_num + 1));
2013                         if (tmp == NULL)
2014                         {
2015                                 ERROR ("network plugin: realloc failed.");
2016                                 continue;
2017                         }
2018                         se->data.server.fd = tmp;
2019                         tmp = se->data.server.fd + se->data.server.fd_num;
2020
2021                         *tmp = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
2022                                         ai_ptr->ai_protocol);
2023                         if (*tmp < 0)
2024                         {
2025                                 char errbuf[1024];
2026                                 ERROR ("network plugin: socket(2) failed: %s",
2027                                                 sstrerror (errno, errbuf,
2028                                                         sizeof (errbuf)));
2029                                 continue;
2030                         }
2031
2032                         status = network_bind_socket (*tmp, ai_ptr, se->interface);
2033                         if (status != 0)
2034                         {
2035                                 close (*tmp);
2036                                 *tmp = -1;
2037                                 continue;
2038                         }
2039
2040                         se->data.server.fd_num++;
2041                         continue;
2042                 } /* }}} if (se->type == SOCKENT_TYPE_SERVER) */
2043                 else /* if (se->type == SOCKENT_TYPE_CLIENT) {{{ */
2044                 {
2045                         se->data.client.fd = socket (ai_ptr->ai_family,
2046                                         ai_ptr->ai_socktype,
2047                                         ai_ptr->ai_protocol);
2048                         if (se->data.client.fd < 0)
2049                         {
2050                                 char errbuf[1024];
2051                                 ERROR ("network plugin: socket(2) failed: %s",
2052                                                 sstrerror (errno, errbuf,
2053                                                         sizeof (errbuf)));
2054                                 continue;
2055                         }
2056
2057                         se->data.client.addr = malloc (sizeof (*se->data.client.addr));
2058                         if (se->data.client.addr == NULL)
2059                         {
2060                                 ERROR ("network plugin: malloc failed.");
2061                                 close (se->data.client.fd);
2062                                 se->data.client.fd = -1;
2063                                 continue;
2064                         }
2065
2066                         memset (se->data.client.addr, 0, sizeof (*se->data.client.addr));
2067                         assert (sizeof (*se->data.client.addr) >= ai_ptr->ai_addrlen);
2068                         memcpy (se->data.client.addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
2069                         se->data.client.addrlen = ai_ptr->ai_addrlen;
2070
2071                         network_set_ttl (se, ai_ptr);
2072                         network_set_interface (se, ai_ptr);
2073
2074                         /* We don't open more than one write-socket per
2075                          * node/service pair.. */
2076                         break;
2077                 } /* }}} if (se->type == SOCKENT_TYPE_CLIENT) */
2078         } /* for (ai_list) */
2079
2080         freeaddrinfo (ai_list);
2081
2082         /* Check if all went well. */
2083         if (se->type == SOCKENT_TYPE_SERVER)
2084         {
2085                 if (se->data.server.fd_num <= 0)
2086                         return (-1);
2087         }
2088         else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2089         {
2090                 if (se->data.client.fd < 0)
2091                         return (-1);
2092         }
2093
2094         return (0);
2095 } /* }}} int sockent_open */
2096
2097 /* Add a sockent to the global list of sockets */
2098 static int sockent_add (sockent_t *se) /* {{{ */
2099 {
2100         sockent_t *last_ptr;
2101
2102         if (se == NULL)
2103                 return (-1);
2104
2105         if (se->type == SOCKENT_TYPE_SERVER)
2106         {
2107                 struct pollfd *tmp;
2108                 size_t i;
2109
2110                 tmp = realloc (listen_sockets_pollfd,
2111                                 sizeof (*tmp) * (listen_sockets_num
2112                                         + se->data.server.fd_num));
2113                 if (tmp == NULL)
2114                 {
2115                         ERROR ("network plugin: realloc failed.");
2116                         return (-1);
2117                 }
2118                 listen_sockets_pollfd = tmp;
2119                 tmp = listen_sockets_pollfd + listen_sockets_num;
2120
2121                 for (i = 0; i < se->data.server.fd_num; i++)
2122                 {
2123                         memset (tmp + i, 0, sizeof (*tmp));
2124                         tmp[i].fd = se->data.server.fd[i];
2125                         tmp[i].events = POLLIN | POLLPRI;
2126                         tmp[i].revents = 0;
2127                 }
2128
2129                 listen_sockets_num += se->data.server.fd_num;
2130
2131                 if (listen_sockets == NULL)
2132                 {
2133                         listen_sockets = se;
2134                         return (0);
2135                 }
2136                 last_ptr = listen_sockets;
2137         }
2138         else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2139         {
2140                 if (sending_sockets == NULL)
2141                 {
2142                         sending_sockets = se;
2143                         return (0);
2144                 }
2145                 last_ptr = sending_sockets;
2146         }
2147
2148         while (last_ptr->next != NULL)
2149                 last_ptr = last_ptr->next;
2150         last_ptr->next = se;
2151
2152         return (0);
2153 } /* }}} int sockent_add */
2154
2155 static void *dispatch_thread (void __attribute__((unused)) *arg) /* {{{ */
2156 {
2157   while (42)
2158   {
2159     receive_list_entry_t *ent;
2160     sockent_t *se;
2161
2162     /* Lock and wait for more data to come in */
2163     pthread_mutex_lock (&receive_list_lock);
2164     while ((listen_loop == 0)
2165         && (receive_list_head == NULL))
2166       pthread_cond_wait (&receive_list_cond, &receive_list_lock);
2167
2168     /* Remove the head entry and unlock */
2169     ent = receive_list_head;
2170     if (ent != NULL)
2171       receive_list_head = ent->next;
2172     receive_list_length--;
2173     pthread_mutex_unlock (&receive_list_lock);
2174
2175     /* Check whether we are supposed to exit. We do NOT check `listen_loop'
2176      * because we dispatch all missing packets before shutting down. */
2177     if (ent == NULL)
2178       break;
2179
2180     /* Look for the correct `sockent_t' */
2181     se = listen_sockets;
2182     while (se != NULL)
2183     {
2184       size_t i;
2185
2186       for (i = 0; i < se->data.server.fd_num; i++)
2187         if (se->data.server.fd[i] == ent->fd)
2188           break;
2189
2190       if (i < se->data.server.fd_num)
2191         break;
2192
2193       se = se->next;
2194     }
2195
2196     if (se == NULL)
2197     {
2198       ERROR ("network plugin: Got packet from FD %i, but can't "
2199           "find an appropriate socket entry.",
2200           ent->fd);
2201       sfree (ent->data);
2202       sfree (ent);
2203       continue;
2204     }
2205
2206     parse_packet (se, ent->data, ent->data_len, /* flags = */ 0,
2207         /* username = */ NULL);
2208     sfree (ent->data);
2209     sfree (ent);
2210   } /* while (42) */
2211
2212   return (NULL);
2213 } /* }}} void *dispatch_thread */
2214
2215 static int network_receive (void) /* {{{ */
2216 {
2217         char buffer[network_config_packet_size];
2218         int  buffer_len;
2219
2220         int i;
2221         int status;
2222
2223         receive_list_entry_t *private_list_head;
2224         receive_list_entry_t *private_list_tail;
2225         uint64_t              private_list_length;
2226
2227         assert (listen_sockets_num > 0);
2228
2229         private_list_head = NULL;
2230         private_list_tail = NULL;
2231         private_list_length = 0;
2232
2233         while (listen_loop == 0)
2234         {
2235                 status = poll (listen_sockets_pollfd, listen_sockets_num, -1);
2236
2237                 if (status <= 0)
2238                 {
2239                         char errbuf[1024];
2240                         if (errno == EINTR)
2241                                 continue;
2242                         ERROR ("poll failed: %s",
2243                                         sstrerror (errno, errbuf, sizeof (errbuf)));
2244                         return (-1);
2245                 }
2246
2247                 for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
2248                 {
2249                         receive_list_entry_t *ent;
2250
2251                         if ((listen_sockets_pollfd[i].revents
2252                                                 & (POLLIN | POLLPRI)) == 0)
2253                                 continue;
2254                         status--;
2255
2256                         buffer_len = recv (listen_sockets_pollfd[i].fd,
2257                                         buffer, sizeof (buffer),
2258                                         0 /* no flags */);
2259                         if (buffer_len < 0)
2260                         {
2261                                 char errbuf[1024];
2262                                 ERROR ("recv failed: %s",
2263                                                 sstrerror (errno, errbuf,
2264                                                         sizeof (errbuf)));
2265                                 return (-1);
2266                         }
2267
2268                         stats_octets_rx += ((uint64_t) buffer_len);
2269                         stats_packets_rx++;
2270
2271                         /* TODO: Possible performance enhancement: Do not free
2272                          * these entries in the dispatch thread but put them in
2273                          * another list, so we don't have to allocate more and
2274                          * more of these structures. */
2275                         ent = malloc (sizeof (receive_list_entry_t));
2276                         if (ent == NULL)
2277                         {
2278                                 ERROR ("network plugin: malloc failed.");
2279                                 return (-1);
2280                         }
2281                         memset (ent, 0, sizeof (receive_list_entry_t));
2282                         ent->data = malloc (network_config_packet_size);
2283                         if (ent->data == NULL)
2284                         {
2285                                 sfree (ent);
2286                                 ERROR ("network plugin: malloc failed.");
2287                                 return (-1);
2288                         }
2289                         ent->fd = listen_sockets_pollfd[i].fd;
2290                         ent->next = NULL;
2291
2292                         memcpy (ent->data, buffer, buffer_len);
2293                         ent->data_len = buffer_len;
2294
2295                         if (private_list_head == NULL)
2296                                 private_list_head = ent;
2297                         else
2298                                 private_list_tail->next = ent;
2299                         private_list_tail = ent;
2300                         private_list_length++;
2301
2302                         /* Do not block here. Blocking here has led to
2303                          * insufficient performance in the past. */
2304                         if (pthread_mutex_trylock (&receive_list_lock) == 0)
2305                         {
2306                                 assert (((receive_list_head == NULL) && (receive_list_length == 0))
2307                                                 || ((receive_list_head != NULL) && (receive_list_length != 0)));
2308
2309                                 if (receive_list_head == NULL)
2310                                         receive_list_head = private_list_head;
2311                                 else
2312                                         receive_list_tail->next = private_list_head;
2313                                 receive_list_tail = private_list_tail;
2314                                 receive_list_length += private_list_length;
2315
2316                                 pthread_cond_signal (&receive_list_cond);
2317                                 pthread_mutex_unlock (&receive_list_lock);
2318
2319                                 private_list_head = NULL;
2320                                 private_list_tail = NULL;
2321                                 private_list_length = 0;
2322                         }
2323                 } /* for (listen_sockets_pollfd) */
2324         } /* while (listen_loop == 0) */
2325
2326         /* Make sure everything is dispatched before exiting. */
2327         if (private_list_head != NULL)
2328         {
2329                 pthread_mutex_lock (&receive_list_lock);
2330
2331                 if (receive_list_head == NULL)
2332                         receive_list_head = private_list_head;
2333                 else
2334                         receive_list_tail->next = private_list_head;
2335                 receive_list_tail = private_list_tail;
2336                 receive_list_length += private_list_length;
2337
2338                 private_list_head = NULL;
2339                 private_list_tail = NULL;
2340                 private_list_length = 0;
2341
2342                 pthread_cond_signal (&receive_list_cond);
2343                 pthread_mutex_unlock (&receive_list_lock);
2344         }
2345
2346         return (0);
2347 } /* }}} int network_receive */
2348
2349 static void *receive_thread (void __attribute__((unused)) *arg)
2350 {
2351         return (network_receive () ? (void *) 1 : (void *) 0);
2352 } /* void *receive_thread */
2353
2354 static void network_init_buffer (void)
2355 {
2356         memset (send_buffer, 0, network_config_packet_size);
2357         send_buffer_ptr = send_buffer;
2358         send_buffer_fill = 0;
2359
2360         memset (&send_buffer_vl, 0, sizeof (send_buffer_vl));
2361 } /* int network_init_buffer */
2362
2363 static void networt_send_buffer_plain (const sockent_t *se, /* {{{ */
2364                 const char *buffer, size_t buffer_size)
2365 {
2366         int status;
2367
2368         while (42)
2369         {
2370                 status = sendto (se->data.client.fd, buffer, buffer_size,
2371                     /* flags = */ 0,
2372                     (struct sockaddr *) se->data.client.addr,
2373                     se->data.client.addrlen);
2374                 if (status < 0)
2375                 {
2376                         char errbuf[1024];
2377                         if (errno == EINTR)
2378                                 continue;
2379                         ERROR ("network plugin: sendto failed: %s",
2380                                         sstrerror (errno, errbuf,
2381                                                 sizeof (errbuf)));
2382                         break;
2383                 }
2384
2385                 break;
2386         } /* while (42) */
2387 } /* }}} void networt_send_buffer_plain */
2388
2389 #if HAVE_LIBGCRYPT
2390 #define BUFFER_ADD(p,s) do { \
2391   memcpy (buffer + buffer_offset, (p), (s)); \
2392   buffer_offset += (s); \
2393 } while (0)
2394
2395 static void networt_send_buffer_signed (const sockent_t *se, /* {{{ */
2396                 const char *in_buffer, size_t in_buffer_size)
2397 {
2398   part_signature_sha256_t ps;
2399   char buffer[BUFF_SIG_SIZE + in_buffer_size];
2400   size_t buffer_offset;
2401   size_t username_len;
2402
2403   gcry_md_hd_t hd;
2404   gcry_error_t err;
2405   unsigned char *hash;
2406
2407   hd = NULL;
2408   err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
2409   if (err != 0)
2410   {
2411     ERROR ("network plugin: Creating HMAC object failed: %s",
2412         gcry_strerror (err));
2413     return;
2414   }
2415
2416   err = gcry_md_setkey (hd, se->data.client.password,
2417       strlen (se->data.client.password));
2418   if (err != 0)
2419   {
2420     ERROR ("network plugin: gcry_md_setkey failed: %s",
2421         gcry_strerror (err));
2422     gcry_md_close (hd);
2423     return;
2424   }
2425
2426   username_len = strlen (se->data.client.username);
2427   if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE))
2428   {
2429     ERROR ("network plugin: Username too long: %s",
2430         se->data.client.username);
2431     return;
2432   }
2433
2434   memcpy (buffer + PART_SIGNATURE_SHA256_SIZE,
2435       se->data.client.username, username_len);
2436   memcpy (buffer + PART_SIGNATURE_SHA256_SIZE + username_len,
2437       in_buffer, in_buffer_size);
2438
2439   /* Initialize the `ps' structure. */
2440   memset (&ps, 0, sizeof (ps));
2441   ps.head.type = htons (TYPE_SIGN_SHA256);
2442   ps.head.length = htons (PART_SIGNATURE_SHA256_SIZE + username_len);
2443
2444   /* Calculate the hash value. */
2445   gcry_md_write (hd, buffer + PART_SIGNATURE_SHA256_SIZE,
2446       username_len + in_buffer_size);
2447   hash = gcry_md_read (hd, GCRY_MD_SHA256);
2448   if (hash == NULL)
2449   {
2450     ERROR ("network plugin: gcry_md_read failed.");
2451     gcry_md_close (hd);
2452     return;
2453   }
2454   memcpy (ps.hash, hash, sizeof (ps.hash));
2455
2456   /* Add the header */
2457   buffer_offset = 0;
2458
2459   BUFFER_ADD (&ps.head.type, sizeof (ps.head.type));
2460   BUFFER_ADD (&ps.head.length, sizeof (ps.head.length));
2461   BUFFER_ADD (ps.hash, sizeof (ps.hash));
2462
2463   assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
2464
2465   gcry_md_close (hd);
2466   hd = NULL;
2467
2468   buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
2469   networt_send_buffer_plain (se, buffer, buffer_offset);
2470 } /* }}} void networt_send_buffer_signed */
2471
2472 static void networt_send_buffer_encrypted (sockent_t *se, /* {{{ */
2473                 const char *in_buffer, size_t in_buffer_size)
2474 {
2475   part_encryption_aes256_t pea;
2476   char buffer[BUFF_SIG_SIZE + in_buffer_size];
2477   size_t buffer_size;
2478   size_t buffer_offset;
2479   size_t header_size;
2480   size_t username_len;
2481   gcry_error_t err;
2482   gcry_cipher_hd_t cypher;
2483
2484   /* Initialize the header fields */
2485   memset (&pea, 0, sizeof (pea));
2486   pea.head.type = htons (TYPE_ENCR_AES256);
2487
2488   pea.username = se->data.client.username;
2489
2490   username_len = strlen (pea.username);
2491   if ((PART_ENCRYPTION_AES256_SIZE + username_len) > BUFF_SIG_SIZE)
2492   {
2493     ERROR ("network plugin: Username too long: %s", pea.username);
2494     return;
2495   }
2496
2497   buffer_size = PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size;
2498   header_size = PART_ENCRYPTION_AES256_SIZE + username_len
2499     - sizeof (pea.hash);
2500
2501   assert (buffer_size <= sizeof (buffer));
2502   DEBUG ("network plugin: networt_send_buffer_encrypted: "
2503       "buffer_size = %zu;", buffer_size);
2504
2505   pea.head.length = htons ((uint16_t) (PART_ENCRYPTION_AES256_SIZE
2506         + username_len + in_buffer_size));
2507   pea.username_length = htons ((uint16_t) username_len);
2508
2509   /* Chose a random initialization vector. */
2510   gcry_randomize ((void *) &pea.iv, sizeof (pea.iv), GCRY_STRONG_RANDOM);
2511
2512   /* Create hash of the payload */
2513   gcry_md_hash_buffer (GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
2514
2515   /* Initialize the buffer */
2516   buffer_offset = 0;
2517   memset (buffer, 0, sizeof (buffer));
2518
2519
2520   BUFFER_ADD (&pea.head.type, sizeof (pea.head.type));
2521   BUFFER_ADD (&pea.head.length, sizeof (pea.head.length));
2522   BUFFER_ADD (&pea.username_length, sizeof (pea.username_length));
2523   BUFFER_ADD (pea.username, username_len);
2524   BUFFER_ADD (pea.iv, sizeof (pea.iv));
2525   assert (buffer_offset == header_size);
2526   BUFFER_ADD (pea.hash, sizeof (pea.hash));
2527   BUFFER_ADD (in_buffer, in_buffer_size);
2528
2529   assert (buffer_offset == buffer_size);
2530
2531   cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
2532       se->data.client.password);
2533   if (cypher == NULL)
2534     return;
2535
2536   /* Encrypt the buffer in-place */
2537   err = gcry_cipher_encrypt (cypher,
2538       buffer      + header_size,
2539       buffer_size - header_size,
2540       /* in = */ NULL, /* in len = */ 0);
2541   if (err != 0)
2542   {
2543     ERROR ("network plugin: gcry_cipher_encrypt returned: %s",
2544         gcry_strerror (err));
2545     return;
2546   }
2547
2548   /* Send it out without further modifications */
2549   networt_send_buffer_plain (se, buffer, buffer_size);
2550 } /* }}} void networt_send_buffer_encrypted */
2551 #undef BUFFER_ADD
2552 #endif /* HAVE_LIBGCRYPT */
2553
2554 static void network_send_buffer (char *buffer, size_t buffer_len) /* {{{ */
2555 {
2556   sockent_t *se;
2557
2558   DEBUG ("network plugin: network_send_buffer: buffer_len = %zu", buffer_len);
2559
2560   for (se = sending_sockets; se != NULL; se = se->next)
2561   {
2562 #if HAVE_LIBGCRYPT
2563     if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
2564       networt_send_buffer_encrypted (se, buffer, buffer_len);
2565     else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
2566       networt_send_buffer_signed (se, buffer, buffer_len);
2567     else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
2568 #endif /* HAVE_LIBGCRYPT */
2569       networt_send_buffer_plain (se, buffer, buffer_len);
2570   } /* for (sending_sockets) */
2571 } /* }}} void network_send_buffer */
2572
2573 static int add_to_buffer (char *buffer, int buffer_size, /* {{{ */
2574                 value_list_t *vl_def,
2575                 const data_set_t *ds, const value_list_t *vl)
2576 {
2577         char *buffer_orig = buffer;
2578
2579         if (strcmp (vl_def->host, vl->host) != 0)
2580         {
2581                 if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
2582                                         vl->host, strlen (vl->host)) != 0)
2583                         return (-1);
2584                 sstrncpy (vl_def->host, vl->host, sizeof (vl_def->host));
2585         }
2586
2587         if (vl_def->time != vl->time)
2588         {
2589                 if (write_part_number (&buffer, &buffer_size, TYPE_TIME,
2590                                         (uint64_t) vl->time))
2591                         return (-1);
2592                 vl_def->time = vl->time;
2593         }
2594
2595         if (vl_def->interval != vl->interval)
2596         {
2597                 if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL,
2598                                         (uint64_t) vl->interval))
2599                         return (-1);
2600                 vl_def->interval = vl->interval;
2601         }
2602
2603         if (strcmp (vl_def->plugin, vl->plugin) != 0)
2604         {
2605                 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
2606                                         vl->plugin, strlen (vl->plugin)) != 0)
2607                         return (-1);
2608                 sstrncpy (vl_def->plugin, vl->plugin, sizeof (vl_def->plugin));
2609         }
2610
2611         if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
2612         {
2613                 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
2614                                         vl->plugin_instance,
2615                                         strlen (vl->plugin_instance)) != 0)
2616                         return (-1);
2617                 sstrncpy (vl_def->plugin_instance, vl->plugin_instance, sizeof (vl_def->plugin_instance));
2618         }
2619
2620         if (strcmp (vl_def->type, vl->type) != 0)
2621         {
2622                 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
2623                                         vl->type, strlen (vl->type)) != 0)
2624                         return (-1);
2625                 sstrncpy (vl_def->type, ds->type, sizeof (vl_def->type));
2626         }
2627
2628         if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
2629         {
2630                 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
2631                                         vl->type_instance,
2632                                         strlen (vl->type_instance)) != 0)
2633                         return (-1);
2634                 sstrncpy (vl_def->type_instance, vl->type_instance, sizeof (vl_def->type_instance));
2635         }
2636         
2637         if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
2638                 return (-1);
2639
2640         return (buffer - buffer_orig);
2641 } /* }}} int add_to_buffer */
2642
2643 static void flush_buffer (void)
2644 {
2645         DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
2646                         send_buffer_fill);
2647
2648         network_send_buffer (send_buffer, (size_t) send_buffer_fill);
2649
2650         stats_octets_tx += ((uint64_t) send_buffer_fill);
2651         stats_packets_tx++;
2652
2653         network_init_buffer ();
2654 }
2655
2656 static int network_write (const data_set_t *ds, const value_list_t *vl,
2657                 user_data_t __attribute__((unused)) *user_data)
2658 {
2659         int status;
2660
2661         if (!check_send_okay (vl))
2662         {
2663 #if COLLECT_DEBUG
2664           char name[6*DATA_MAX_NAME_LEN];
2665           FORMAT_VL (name, sizeof (name), vl);
2666           name[sizeof (name) - 1] = 0;
2667           DEBUG ("network plugin: network_write: "
2668               "NOT sending %s.", name);
2669 #endif
2670           /* Counter is not protected by another lock and may be reached by
2671            * multiple threads */
2672           pthread_mutex_lock (&stats_lock);
2673           stats_values_not_sent++;
2674           pthread_mutex_unlock (&stats_lock);
2675           return (0);
2676         }
2677
2678         uc_meta_data_add_unsigned_int (vl,
2679             "network:time_sent", (uint64_t) vl->time);
2680
2681         pthread_mutex_lock (&send_buffer_lock);
2682
2683         status = add_to_buffer (send_buffer_ptr,
2684                         network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2685                         &send_buffer_vl,
2686                         ds, vl);
2687         if (status >= 0)
2688         {
2689                 /* status == bytes added to the buffer */
2690                 send_buffer_fill += status;
2691                 send_buffer_ptr  += status;
2692
2693                 stats_values_sent++;
2694         }
2695         else
2696         {
2697                 flush_buffer ();
2698
2699                 status = add_to_buffer (send_buffer_ptr,
2700                                 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2701                                 &send_buffer_vl,
2702                                 ds, vl);
2703
2704                 if (status >= 0)
2705                 {
2706                         send_buffer_fill += status;
2707                         send_buffer_ptr  += status;
2708
2709                         stats_values_sent++;
2710                 }
2711         }
2712
2713         if (status < 0)
2714         {
2715                 ERROR ("network plugin: Unable to append to the "
2716                                 "buffer for some weird reason");
2717         }
2718         else if (send_buffer_fill >= 1452 - 15)
2719         {
2720                 flush_buffer ();
2721         }
2722
2723         pthread_mutex_unlock (&send_buffer_lock);
2724
2725         return ((status < 0) ? -1 : 0);
2726 } /* int network_write */
2727
2728 static int network_config_set_boolean (const oconfig_item_t *ci, /* {{{ */
2729     int *retval)
2730 {
2731   if ((ci->values_num != 1)
2732       || ((ci->values[0].type != OCONFIG_TYPE_BOOLEAN)
2733         && (ci->values[0].type != OCONFIG_TYPE_STRING)))
2734   {
2735     ERROR ("network plugin: The `%s' config option needs "
2736         "exactly one boolean argument.", ci->key);
2737     return (-1);
2738   }
2739
2740   if (ci->values[0].type == OCONFIG_TYPE_BOOLEAN)
2741   {
2742     if (ci->values[0].value.boolean)
2743       *retval = 1;
2744     else
2745       *retval = 0;
2746   }
2747   else
2748   {
2749     char *str = ci->values[0].value.string;
2750
2751     if (IS_TRUE (str))
2752       *retval = 1;
2753     else if (IS_FALSE (str))
2754       *retval = 0;
2755     else
2756     {
2757       ERROR ("network plugin: Cannot parse string value `%s' of the `%s' "
2758           "option as boolean value.",
2759           str, ci->key);
2760       return (-1);
2761     }
2762   }
2763
2764   return (0);
2765 } /* }}} int network_config_set_boolean */
2766
2767 static int network_config_set_ttl (const oconfig_item_t *ci) /* {{{ */
2768 {
2769   int tmp;
2770   if ((ci->values_num != 1)
2771       || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2772   {
2773     WARNING ("network plugin: The `TimeToLive' config option needs exactly "
2774         "one numeric argument.");
2775     return (-1);
2776   }
2777
2778   tmp = (int) ci->values[0].value.number;
2779   if ((tmp > 0) && (tmp <= 255))
2780     network_config_ttl = tmp;
2781
2782   return (0);
2783 } /* }}} int network_config_set_ttl */
2784
2785 static int network_config_set_interface (const oconfig_item_t *ci, /* {{{ */
2786     int *interface)
2787 {
2788   if ((ci->values_num != 1)
2789       || (ci->values[0].type != OCONFIG_TYPE_STRING))
2790   {
2791     WARNING ("network plugin: The `Interface' config option needs exactly "
2792         "one string argument.");
2793     return (-1);
2794   }
2795
2796   if (interface == NULL)
2797     return (-1);
2798
2799   *interface = if_nametoindex (ci->values[0].value.string);
2800
2801   return (0);
2802 } /* }}} int network_config_set_interface */
2803
2804 static int network_config_set_buffer_size (const oconfig_item_t *ci) /* {{{ */
2805 {
2806   int tmp;
2807   if ((ci->values_num != 1)
2808       || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2809   {
2810     WARNING ("network plugin: The `MaxPacketSize' config option needs exactly "
2811         "one numeric argument.");
2812     return (-1);
2813   }
2814
2815   tmp = (int) ci->values[0].value.number;
2816   if ((tmp >= 1024) && (tmp <= 65535))
2817     network_config_packet_size = tmp;
2818
2819   return (0);
2820 } /* }}} int network_config_set_buffer_size */
2821
2822 #if HAVE_LIBGCRYPT
2823 static int network_config_set_string (const oconfig_item_t *ci, /* {{{ */
2824     char **ret_string)
2825 {
2826   char *tmp;
2827   if ((ci->values_num != 1)
2828       || (ci->values[0].type != OCONFIG_TYPE_STRING))
2829   {
2830     WARNING ("network plugin: The `%s' config option needs exactly "
2831         "one string argument.", ci->key);
2832     return (-1);
2833   }
2834
2835   tmp = strdup (ci->values[0].value.string);
2836   if (tmp == NULL)
2837     return (-1);
2838
2839   sfree (*ret_string);
2840   *ret_string = tmp;
2841
2842   return (0);
2843 } /* }}} int network_config_set_string */
2844 #endif /* HAVE_LIBGCRYPT */
2845
2846 #if HAVE_LIBGCRYPT
2847 static int network_config_set_security_level (oconfig_item_t *ci, /* {{{ */
2848     int *retval)
2849 {
2850   char *str;
2851   if ((ci->values_num != 1)
2852       || (ci->values[0].type != OCONFIG_TYPE_STRING))
2853   {
2854     WARNING ("network plugin: The `SecurityLevel' config option needs exactly "
2855         "one string argument.");
2856     return (-1);
2857   }
2858
2859   str = ci->values[0].value.string;
2860   if (strcasecmp ("Encrypt", str) == 0)
2861     *retval = SECURITY_LEVEL_ENCRYPT;
2862   else if (strcasecmp ("Sign", str) == 0)
2863     *retval = SECURITY_LEVEL_SIGN;
2864   else if (strcasecmp ("None", str) == 0)
2865     *retval = SECURITY_LEVEL_NONE;
2866   else
2867   {
2868     WARNING ("network plugin: Unknown security level: %s.", str);
2869     return (-1);
2870   }
2871
2872   return (0);
2873 } /* }}} int network_config_set_security_level */
2874 #endif /* HAVE_LIBGCRYPT */
2875
2876 static int network_config_add_listen (const oconfig_item_t *ci) /* {{{ */
2877 {
2878   sockent_t *se;
2879   int status;
2880   int i;
2881
2882   if ((ci->values_num < 1) || (ci->values_num > 2)
2883       || (ci->values[0].type != OCONFIG_TYPE_STRING)
2884       || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
2885   {
2886     ERROR ("network plugin: The `%s' config option needs "
2887         "one or two string arguments.", ci->key);
2888     return (-1);
2889   }
2890
2891   se = malloc (sizeof (*se));
2892   if (se == NULL)
2893   {
2894     ERROR ("network plugin: malloc failed.");
2895     return (-1);
2896   }
2897   sockent_init (se, SOCKENT_TYPE_SERVER);
2898
2899   se->node = strdup (ci->values[0].value.string);
2900   if (ci->values_num >= 2)
2901     se->service = strdup (ci->values[1].value.string);
2902
2903   for (i = 0; i < ci->children_num; i++)
2904   {
2905     oconfig_item_t *child = ci->children + i;
2906
2907 #if HAVE_LIBGCRYPT
2908     if (strcasecmp ("AuthFile", child->key) == 0)
2909       network_config_set_string (child, &se->data.server.auth_file);
2910     else if (strcasecmp ("SecurityLevel", child->key) == 0)
2911       network_config_set_security_level (child,
2912           &se->data.server.security_level);
2913     else
2914 #endif /* HAVE_LIBGCRYPT */
2915     if (strcasecmp ("Interface", child->key) == 0)
2916       network_config_set_interface (child,
2917           &se->interface);
2918     else
2919     {
2920       WARNING ("network plugin: Option `%s' is not allowed here.",
2921           child->key);
2922     }
2923   }
2924
2925 #if HAVE_LIBGCRYPT
2926   if ((se->data.server.security_level > SECURITY_LEVEL_NONE)
2927       && (se->data.server.auth_file == NULL))
2928   {
2929     ERROR ("network plugin: A security level higher than `none' was "
2930         "requested, but no AuthFile option was given. Cowardly refusing to "
2931         "open this socket!");
2932     sockent_destroy (se);
2933     return (-1);
2934   }
2935 #endif /* HAVE_LIBGCRYPT */
2936
2937   status = sockent_open (se);
2938   if (status != 0)
2939   {
2940     ERROR ("network plugin: network_config_add_listen: sockent_open failed.");
2941     sockent_destroy (se);
2942     return (-1);
2943   }
2944
2945   status = sockent_add (se);
2946   if (status != 0)
2947   {
2948     ERROR ("network plugin: network_config_add_listen: sockent_add failed.");
2949     sockent_destroy (se);
2950     return (-1);
2951   }
2952
2953   return (0);
2954 } /* }}} int network_config_add_listen */
2955
2956 static int network_config_add_server (const oconfig_item_t *ci) /* {{{ */
2957 {
2958   sockent_t *se;
2959   int status;
2960   int i;
2961
2962   if ((ci->values_num < 1) || (ci->values_num > 2)
2963       || (ci->values[0].type != OCONFIG_TYPE_STRING)
2964       || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
2965   {
2966     ERROR ("network plugin: The `%s' config option needs "
2967         "one or two string arguments.", ci->key);
2968     return (-1);
2969   }
2970
2971   se = malloc (sizeof (*se));
2972   if (se == NULL)
2973   {
2974     ERROR ("network plugin: malloc failed.");
2975     return (-1);
2976   }
2977   sockent_init (se, SOCKENT_TYPE_CLIENT);
2978
2979   se->node = strdup (ci->values[0].value.string);
2980   if (ci->values_num >= 2)
2981     se->service = strdup (ci->values[1].value.string);
2982
2983   for (i = 0; i < ci->children_num; i++)
2984   {
2985     oconfig_item_t *child = ci->children + i;
2986
2987 #if HAVE_LIBGCRYPT
2988     if (strcasecmp ("Username", child->key) == 0)
2989       network_config_set_string (child, &se->data.client.username);
2990     else if (strcasecmp ("Password", child->key) == 0)
2991       network_config_set_string (child, &se->data.client.password);
2992     else if (strcasecmp ("SecurityLevel", child->key) == 0)
2993       network_config_set_security_level (child,
2994           &se->data.client.security_level);
2995     else
2996 #endif /* HAVE_LIBGCRYPT */
2997     if (strcasecmp ("Interface", child->key) == 0)
2998       network_config_set_interface (child,
2999           &se->interface);
3000     else
3001     {
3002       WARNING ("network plugin: Option `%s' is not allowed here.",
3003           child->key);
3004     }
3005   }
3006
3007 #if HAVE_LIBGCRYPT
3008   if ((se->data.client.security_level > SECURITY_LEVEL_NONE)
3009       && ((se->data.client.username == NULL)
3010         || (se->data.client.password == NULL)))
3011   {
3012     ERROR ("network plugin: A security level higher than `none' was "
3013         "requested, but no Username or Password option was given. "
3014         "Cowardly refusing to open this socket!");
3015     sockent_destroy (se);
3016     return (-1);
3017   }
3018 #endif /* HAVE_LIBGCRYPT */
3019
3020   status = sockent_open (se);
3021   if (status != 0)
3022   {
3023     ERROR ("network plugin: network_config_add_server: sockent_open failed.");
3024     sockent_destroy (se);
3025     return (-1);
3026   }
3027
3028   status = sockent_add (se);
3029   if (status != 0)
3030   {
3031     ERROR ("network plugin: network_config_add_server: sockent_add failed.");
3032     sockent_destroy (se);
3033     return (-1);
3034   }
3035
3036   return (0);
3037 } /* }}} int network_config_add_server */
3038
3039 static int network_config (oconfig_item_t *ci) /* {{{ */
3040 {
3041   int i;
3042
3043   for (i = 0; i < ci->children_num; i++)
3044   {
3045     oconfig_item_t *child = ci->children + i;
3046
3047     if (strcasecmp ("Listen", child->key) == 0)
3048       network_config_add_listen (child);
3049     else if (strcasecmp ("Server", child->key) == 0)
3050       network_config_add_server (child);
3051     else if (strcasecmp ("TimeToLive", child->key) == 0)
3052       network_config_set_ttl (child);
3053     else if (strcasecmp ("MaxPacketSize", child->key) == 0)
3054       network_config_set_buffer_size (child);
3055     else if (strcasecmp ("Forward", child->key) == 0)
3056       network_config_set_boolean (child, &network_config_forward);
3057     else if (strcasecmp ("ReportStats", child->key) == 0)
3058       network_config_set_boolean (child, &network_config_stats);
3059     else if (strcasecmp ("CacheFlush", child->key) == 0)
3060       /* no op for backwards compatibility only */;
3061     else
3062     {
3063       WARNING ("network plugin: Option `%s' is not allowed here.",
3064           child->key);
3065     }
3066   }
3067
3068   return (0);
3069 } /* }}} int network_config */
3070
3071 static int network_notification (const notification_t *n,
3072                 user_data_t __attribute__((unused)) *user_data)
3073 {
3074   char  buffer[network_config_packet_size];
3075   char *buffer_ptr = buffer;
3076   int   buffer_free = sizeof (buffer);
3077   int   status;
3078
3079   memset (buffer, '\0', sizeof (buffer));
3080
3081
3082   status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME,
3083       (uint64_t) n->time);
3084   if (status != 0)
3085     return (-1);
3086
3087   status = write_part_number (&buffer_ptr, &buffer_free, TYPE_SEVERITY,
3088       (uint64_t) n->severity);
3089   if (status != 0)
3090     return (-1);
3091
3092   if (strlen (n->host) > 0)
3093   {
3094     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_HOST,
3095         n->host, strlen (n->host));
3096     if (status != 0)
3097       return (-1);
3098   }
3099
3100   if (strlen (n->plugin) > 0)
3101   {
3102     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_PLUGIN,
3103         n->plugin, strlen (n->plugin));
3104     if (status != 0)
3105       return (-1);
3106   }
3107
3108   if (strlen (n->plugin_instance) > 0)
3109   {
3110     status = write_part_string (&buffer_ptr, &buffer_free,
3111         TYPE_PLUGIN_INSTANCE,
3112         n->plugin_instance, strlen (n->plugin_instance));
3113     if (status != 0)
3114       return (-1);
3115   }
3116
3117   if (strlen (n->type) > 0)
3118   {
3119     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE,
3120         n->type, strlen (n->type));
3121     if (status != 0)
3122       return (-1);
3123   }
3124
3125   if (strlen (n->type_instance) > 0)
3126   {
3127     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
3128         n->type_instance, strlen (n->type_instance));
3129     if (status != 0)
3130       return (-1);
3131   }
3132
3133   status = write_part_string (&buffer_ptr, &buffer_free, TYPE_MESSAGE,
3134       n->message, strlen (n->message));
3135   if (status != 0)
3136     return (-1);
3137
3138   network_send_buffer (buffer, sizeof (buffer) - buffer_free);
3139
3140   return (0);
3141 } /* int network_notification */
3142
3143 static int network_shutdown (void)
3144 {
3145         listen_loop++;
3146
3147         /* Kill the listening thread */
3148         if (receive_thread_running != 0)
3149         {
3150                 INFO ("network plugin: Stopping receive thread.");
3151                 pthread_kill (receive_thread_id, SIGTERM);
3152                 pthread_join (receive_thread_id, NULL /* no return value */);
3153                 memset (&receive_thread_id, 0, sizeof (receive_thread_id));
3154                 receive_thread_running = 0;
3155         }
3156
3157         /* Shutdown the dispatching thread */
3158         if (dispatch_thread_running != 0)
3159         {
3160                 INFO ("network plugin: Stopping dispatch thread.");
3161                 pthread_mutex_lock (&receive_list_lock);
3162                 pthread_cond_broadcast (&receive_list_cond);
3163                 pthread_mutex_unlock (&receive_list_lock);
3164                 pthread_join (dispatch_thread_id, /* ret = */ NULL);
3165                 dispatch_thread_running = 0;
3166         }
3167
3168         sockent_destroy (listen_sockets);
3169
3170         if (send_buffer_fill > 0)
3171                 flush_buffer ();
3172
3173         sfree (send_buffer);
3174
3175         /* TODO: Close `sending_sockets' */
3176
3177         plugin_unregister_config ("network");
3178         plugin_unregister_init ("network");
3179         plugin_unregister_write ("network");
3180         plugin_unregister_shutdown ("network");
3181
3182         return (0);
3183 } /* int network_shutdown */
3184
3185 static int network_stats_read (void) /* {{{ */
3186 {
3187         uint64_t copy_octets_rx;
3188         uint64_t copy_octets_tx;
3189         uint64_t copy_packets_rx;
3190         uint64_t copy_packets_tx;
3191         uint64_t copy_values_dispatched;
3192         uint64_t copy_values_not_dispatched;
3193         uint64_t copy_values_sent;
3194         uint64_t copy_values_not_sent;
3195         uint64_t copy_receive_list_length;
3196         value_list_t vl = VALUE_LIST_INIT;
3197         value_t values[2];
3198
3199         copy_octets_rx = stats_octets_rx;
3200         copy_octets_tx = stats_octets_tx;
3201         copy_packets_rx = stats_packets_rx;
3202         copy_packets_tx = stats_packets_tx;
3203         copy_values_dispatched = stats_values_dispatched;
3204         copy_values_not_dispatched = stats_values_not_dispatched;
3205         copy_values_sent = stats_values_sent;
3206         copy_values_not_sent = stats_values_not_sent;
3207         copy_receive_list_length = receive_list_length;
3208
3209         /* Initialize `vl' */
3210         vl.values = values;
3211         vl.values_len = 2;
3212         vl.time = 0;
3213         vl.interval = interval_g;
3214         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
3215         sstrncpy (vl.plugin, "network", sizeof (vl.plugin));
3216
3217         /* Octets received / sent */
3218         vl.values[0].counter = (counter_t) copy_octets_rx;
3219         vl.values[1].counter = (counter_t) copy_octets_tx;
3220         sstrncpy (vl.type, "if_octets", sizeof (vl.type));
3221         plugin_dispatch_values_secure (&vl);
3222
3223         /* Packets received / send */
3224         vl.values[0].counter = (counter_t) copy_packets_rx;
3225         vl.values[1].counter = (counter_t) copy_packets_tx;
3226         sstrncpy (vl.type, "if_packets", sizeof (vl.type));
3227         plugin_dispatch_values_secure (&vl);
3228
3229         /* Values (not) dispatched and (not) send */
3230         sstrncpy (vl.type, "total_values", sizeof (vl.type));
3231         vl.values_len = 1;
3232
3233         vl.values[0].derive = (derive_t) copy_values_dispatched;
3234         sstrncpy (vl.type_instance, "dispatch-accepted",
3235                         sizeof (vl.type_instance));
3236         plugin_dispatch_values_secure (&vl);
3237
3238         vl.values[0].derive = (derive_t) copy_values_not_dispatched;
3239         sstrncpy (vl.type_instance, "dispatch-rejected",
3240                         sizeof (vl.type_instance));
3241         plugin_dispatch_values_secure (&vl);
3242
3243         vl.values[0].derive = (derive_t) copy_values_sent;
3244         sstrncpy (vl.type_instance, "send-accepted",
3245                         sizeof (vl.type_instance));
3246         plugin_dispatch_values_secure (&vl);
3247
3248         vl.values[0].derive = (derive_t) copy_values_not_sent;
3249         sstrncpy (vl.type_instance, "send-rejected",
3250                         sizeof (vl.type_instance));
3251         plugin_dispatch_values_secure (&vl);
3252
3253         /* Receive queue length */
3254         vl.values[0].gauge = (gauge_t) copy_receive_list_length;
3255         sstrncpy (vl.type, "queue_length", sizeof (vl.type));
3256         vl.type_instance[0] = 0;
3257         plugin_dispatch_values_secure (&vl);
3258
3259         return (0);
3260 } /* }}} int network_stats_read */
3261
3262 static int network_init (void)
3263 {
3264         static _Bool have_init = false;
3265
3266         /* Check if we were already initialized. If so, just return - there's
3267          * nothing more to do (for now, that is). */
3268         if (have_init)
3269                 return (0);
3270         have_init = true;
3271
3272 #if HAVE_LIBGCRYPT
3273         gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
3274         gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
3275         gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
3276 #endif
3277
3278         if (network_config_stats != 0)
3279                 plugin_register_read ("network", network_stats_read);
3280
3281         plugin_register_shutdown ("network", network_shutdown);
3282
3283         send_buffer = malloc (network_config_packet_size);
3284         if (send_buffer == NULL)
3285         {
3286                 ERROR ("network plugin: malloc failed.");
3287                 return (-1);
3288         }
3289         network_init_buffer ();
3290
3291         /* setup socket(s) and so on */
3292         if (sending_sockets != NULL)
3293         {
3294                 plugin_register_write ("network", network_write,
3295                                 /* user_data = */ NULL);
3296                 plugin_register_notification ("network", network_notification,
3297                                 /* user_data = */ NULL);
3298         }
3299
3300         /* If no threads need to be started, return here. */
3301         if ((listen_sockets_num == 0)
3302                         || ((dispatch_thread_running != 0)
3303                                 && (receive_thread_running != 0)))
3304                 return (0);
3305
3306         if (dispatch_thread_running == 0)
3307         {
3308                 int status;
3309                 status = pthread_create (&dispatch_thread_id,
3310                                 NULL /* no attributes */,
3311                                 dispatch_thread,
3312                                 NULL /* no argument */);
3313                 if (status != 0)
3314                 {
3315                         char errbuf[1024];
3316                         ERROR ("network: pthread_create failed: %s",
3317                                         sstrerror (errno, errbuf,
3318                                                 sizeof (errbuf)));
3319                 }
3320                 else
3321                 {
3322                         dispatch_thread_running = 1;
3323                 }
3324         }
3325
3326         if (receive_thread_running == 0)
3327         {
3328                 int status;
3329                 status = pthread_create (&receive_thread_id,
3330                                 NULL /* no attributes */,
3331                                 receive_thread,
3332                                 NULL /* no argument */);
3333                 if (status != 0)
3334                 {
3335                         char errbuf[1024];
3336                         ERROR ("network: pthread_create failed: %s",
3337                                         sstrerror (errno, errbuf,
3338                                                 sizeof (errbuf)));
3339                 }
3340                 else
3341                 {
3342                         receive_thread_running = 1;
3343                 }
3344         }
3345
3346         return (0);
3347 } /* int network_init */
3348
3349 /* 
3350  * The flush option of the network plugin cannot flush individual identifiers.
3351  * All the values are added to a buffer and sent when the buffer is full, the
3352  * requested value may or may not be in there, it's not worth finding out. We
3353  * just send the buffer if `flush'  is called - if the requested value was in
3354  * there, good. If not, well, then there is nothing to flush.. -octo
3355  */
3356 static int network_flush (int timeout,
3357                 const char __attribute__((unused)) *identifier,
3358                 user_data_t __attribute__((unused)) *user_data)
3359 {
3360         pthread_mutex_lock (&send_buffer_lock);
3361
3362         if (send_buffer_fill > 0)
3363           flush_buffer ();
3364
3365         pthread_mutex_unlock (&send_buffer_lock);
3366
3367         return (0);
3368 } /* int network_flush */
3369
3370 void module_register (void)
3371 {
3372         plugin_register_complex_config ("network", network_config);
3373         plugin_register_init   ("network", network_init);
3374         plugin_register_flush   ("network", network_flush,
3375                         /* user_data = */ NULL);
3376 } /* void module_register */
3377
3378 /* vim: set fdm=marker : */