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