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