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