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