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