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