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