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