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