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