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